Compare commits

..

2 Commits

Author SHA1 Message Date
GiantLuigi4
8df8c6add8 ssr prototyping, no network logic hooked up yet 2023-10-19 17:19:48 -04:00
GiantLuigi4
04ea793021 Update README.md 2023-10-19 11:14:25 -04:00
164 changed files with 4359 additions and 4770 deletions

22
LICENSE
View File

@ -1,21 +1 @@
MIT License This mod and its source code is now in public domain. Feel free to do whatever you want with it; make forks, distribute it... whatever I would appreciate it, of course, if you credited me 😊 Thank you!
Copyright (c) 2023 CinemaMod Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -1,25 +1,9 @@
# WebDisplays # WebDisplays
WebDisplays is a mod for creating and interacting with web browsers in Minecraft. You can create screens in your world and browse the internet. WebDisplays adds a screen block, which allows you to browse the internet in minecraft.
WebDisplays was originally written by montoyo. It is currently maintained by CinemaMod Group. This project is a fork of montoyo's [WebDisplays](https://github.com/montoyo/webdisplays) mod from 1.12, updated to work in newer versions, and with some bug fixes and reworking.
Discussion: https://discord.gg/rNrh5kW8Ty WebDisplays requires [MCEF](https://www.curseforge.com/minecraft/mc-mods/mcef), which is using [CinamaMod's fork of JCEF](https://github.com/CinemaMod/java-cef), which should allow for WD to be a bit more seamless than [Chromium's JCEF](https://github.com/chromiumembedded/java-cef) would allow for.
## Install ### Wiki
Download WebDisplays from either: * A Wiki which details all blocks/items can be found on [montoyo's website](https://montoyo.net/wdwiki/). However, a lot of stuff has changed since that wiki was written.
- CurseForge: https://legacy.curseforge.com/minecraft/mc-mods/webdisplays
- Modrinth: https://modrinth.com/mod/webdisplays
**WebDisplays Requires MCEF!** You must install MCEF in order for WebDisplays to work.
Download MCEF from either:
- CurseForge: https://legacy.curseforge.com/minecraft/mc-mods/mcef
- Modrinth: https://modrinth.com/mod/mcef
<img src='https://github.com/CinemaMod/webdisplays/assets/30220598/2acfd365-fa87-4adb-970a-33bb5c79f7ba' width='500'>
<img src='https://github.com/CinemaMod/webdisplays/assets/30220598/4e9985a3-d09f-4ab4-8016-37733d4f4a99' width='500'>
## Wiki
[Outdated Wiki from the original creator](https://montoyo.net/wdwiki/index.php?title=Main_Page)
[Outdated Getting Started](https://montoyo.net/wdwiki/index.php?title=Screen)

View File

@ -1,179 +1,138 @@
plugins { plugins {
id 'java' id 'eclipse'
id 'idea'
id 'maven-publish' id 'maven-publish'
id 'com.github.johnrengelman.shadow' version '8.1.1' id 'net.neoforged.gradle' version '[6.0.18,6.2)'
id 'net.neoforged.moddev.legacyforge' version '2.0.103' id 'org.spongepowered.mixin' version '0.7.+'
id 'org.parchmentmc.librarian.forgegradle' version '1.+'
} }
// Only add ProGuard if building with it version = mod_version
def enableProguard = project.hasProperty("enableProguard") && project.enableProguard.toBoolean() group = maven_group // http://maven.apache.org/guides/mini/guide-naming-conventions.html
if (enableProguard) { archivesBaseName = archives_base_name
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.guardsquare:proguard-gradle:7.7.0'
}
}
}
base {
archivesName = mod_id
}
group = mod_group_id
version = "${minecraft_version}-${mod_version}"
java.toolchain.languageVersion = JavaLanguageVersion.of(17) java.toolchain.languageVersion = JavaLanguageVersion.of(17)
println "Java: ${System.getProperty 'java.version'}" println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch'))
minecraft {
mappings channel: 'parchment', version: '2023.06.26-1.20.1'
repositories { accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
mavenCentral()
maven { url = "https://libraries.minecraft.net/" }
maven { url = "https://cursemaven.com" }
maven { url = "https://maven.parchmentmc.org" }
maven { url = 'https://mcef-download.cinemamod.com/repositories/releases/' }
maven { url = "https://dl.cloudsmith.io/public/geckolib3/geckolib/maven/" }
maven { url = "https://maven.theillusivec4.top/" }
maven { url = "https://repo.lucko.me/" }
maven { url = "https://maven.kosmx.dev/" }
maven { url = "https://modmaven.dev" }
flatDir { dir "libs" }
}
legacyForge {
version = "${minecraft_version}-${forge_version}"
// Access transformer
accessTransformers = files("src/main/resources/META-INF/accesstransformer.cfg")
// Parchment mappings
parchment {
minecraftVersion = minecraft_version
mappingsVersion = mapping_lasting_version
}
copyIdeResources = true
runs { runs {
configureEach {
systemProperty 'forge.logging.console.level', 'debug'
logLevel = org.slf4j.event.Level.DEBUG
}
client { client {
client() properties 'mixin.env.remapRefMap': 'true'
programArgument "-mixin.config=${mod_id}.mixins.json" property 'mixin.env.refMapRemappingFile', "${project.projectDir}/build/createSrgToMcp/output.srg"
systemProperty 'mixin.debug.export', 'true' workingDirectory project.file('run')
arg "-mixin.config=webdisplays.mixins.json"
property 'forge.logging.console.level', 'debug'
mods {
webdisplays {
source sourceSets.main
}
}
} }
server { server {
server() properties 'mixin.env.remapRefMap': 'true'
programArgument "-mixin.config=${mod_id}.mixins.json" property 'mixin.env.refMapRemappingFile', "${project.projectDir}/build/createSrgToMcp/output.srg"
workingDirectory project.file('run')
arg "-mixin.config=webdisplays.mixins.json"
property 'forge.logging.console.level', 'debug'
mods {
webdisplays {
source sourceSets.main
}
}
} }
data { data {
data() workingDirectory project.file('run')
programArguments.addAll '--mod', mod_id, '--all', properties 'mixin.env.remapRefMap': 'true'
'--output', file('src/generated/resources/').absolutePath, property 'mixin.env.refMapRemappingFile', "${project.projectDir}/build/createSrgToMcp/output.srg"
'--existing', file('src/main/resources/').absolutePath property 'forge.logging.console.level', 'debug'
} args '--mod', 'webdisplays', '--all', '--output', file('src/generated/resources/'), '--existing', sourceSets.main.resources.srcDirs[0]
} mods {
webdisplays {
mods { source sourceSets.main
"${mod_id}" { }
sourceSet sourceSets.main }
} }
} }
} }
sourceSets.main.resources { repositories{
srcDir 'src/generated/resources' maven { url "https://maven.shedaniel.me/" }
maven { url 'https://jitpack.io' }
maven {
name = "cursemaven"
url = "https://www.cursemaven.com"
}
flatDir { dirs 'libs' }
maven { url 'https://mcef-download.cinemamod.com/repository/releases' }
maven { url = uri('https://mcef-download.cinemamod.com/repositories/releases') }
} }
dependencies { dependencies {
// MCEF dependency minecraft 'net.neoforged:forge:1.20.1-47.1.65'
modImplementation("com.cinemamod:mcef-forge:2.1.1-1.20.1") { annotationProcessor 'org.spongepowered:mixin:0.8.5:processor'
transitive = false
}
// Optional mods (make sure versions exist) // implementation fg.deobf("curse.maven:spark-361579:4381167")
modRuntimeOnly "curse.maven:spark-361579:4738952" compileOnly fg.deobf("curse.maven:vivecraft-667903:4794431")
modCompileOnly "curse.maven:vivecraft-667903:4794431"
modImplementation "software.bernie.geckolib:geckolib-forge-${minecraft_version}:${geckolib_version}"
modCompileOnly "top.theillusivec4.curios:curios-forge:${curios_version}:api"
modRuntimeOnly "top.theillusivec4.curios:curios-forge:${curios_version}"
// Mixin Extras // implementation fg.deobf("com.cinemamod:mcef-forge:2.0.1-1.20.1") {
compileOnly annotationProcessor("io.github.llamalad7:mixinextras-common:0.4.1") // transitive = false
modImplementation "io.github.llamalad7:mixinextras-forge:0.4.1" // }
implementation fg.deobf("flatdir.lib:mcef:2.x")
} }
tasks.named('jar', Jar) { sourceSets {
main.resources.srcDirs += 'src/generated/resources'
}
// Example for how to get properties into the manifest for reading by the runtime..
jar {
manifest { manifest {
attributes([ attributes([
'Specification-Title': mod_name, "Specification-Title": "webdisplays",
'Specification-Vendor': mod_authors, "Specification-Vendor": "webdisplays",
'Specification-Version': '1', "Specification-Version": "1", // We are version 1 of ourselves
'Implementation-Title': project.name, "Implementation-Title": project.name,
'Implementation-Version': project.version, "Implementation-Version": "${version}",
'Implementation-Vendor': mod_authors, "Implementation-Vendor" :"webdisplays",
'MixinConfigs': "${mod_id}.mixins.json" "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"),
"MixinConfigs": "webdisplays.mixins.json"
]) ])
} }
// Exclude ProGuard renamed files if ProGuard is used
if (enableProguard) {
exclude 'META-INF/versions/**'
}
} }
// Generate sources jar // Example configuration to allow publishing using the maven-publish task
tasks.register('sourcesJar', Jar) { // we define a custom artifact that is sourced from the reobfJar output task
dependsOn classes // and then declare that to be published
archiveClassifier = 'sources' // Note you'll need to add a repository here
from sourceSets.main.allSource def reobfFile = file("$buildDir/reobfJar/output.jar")
def reobfArtifact = artifacts.add('default', reobfFile) {
type 'jar'
builtBy 'reobfJar'
} }
// Reobfuscation handling
tasks.named('reobfJar') {
if (enableProguard) {
dependsOn 'proguard'
input = file("${buildDir}/libs/${mod_id}-${minecraft_version}-${mod_version}-proguard.jar")
} else {
dependsOn 'jar'
input = tasks.jar.archiveFile.get().asFile
}
}
// ProGuard configuration (if enabled)
if (enableProguard) {
tasks.register('proguard', proguard.gradle.ProGuardTask) {
dependsOn tasks.jar
configuration 'proguard.pro'
libraryjars "${System.getProperty('java.home')}/jmods"
def inputJar = tasks.jar.archiveFile.get().asFile
injars inputJar
outjars "${buildDir}/libs/${mod_id}-${minecraft_version}-${mod_version}-proguard.jar"
}
}
publishing { publishing {
publications { publications {
mavenJava(MavenPublication) { mavenJava(MavenPublication) {
artifactId = mod_id artifact reobfArtifact
artifact reobfJar
artifact sourcesJar
} }
} }
repositories { repositories {
maven { maven {
name = "local" url "file:///${project.projectDir}/mcmodsrepo"
url = layout.buildDirectory.dir("repo")
} }
} }
} }
apply plugin: 'org.spongepowered.mixin'
mixin {
add sourceSets.main, "webdisplays.refmap.json"
}

View File

@ -1,36 +1,17 @@
# Gradle settings # Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx3G org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false loom.platform=forge
org.gradle.parallel=true
org.gradle.caching=true
# ProGuard # Fabric Properties
enableProguard=false # check these on https://fabricmc.net/develop
minecraft_version=1.19.2
yarn_mappings=1.19.2+build.28
loader_version=0.14.14
# Mod properties # Mod Properties
mod_id=webdisplays mod_version = 1.3.3
mod_name=WebDisplays maven_group = net.montoyo.wd
mod_version=2.0.3 archives_base_name = webdisplays
mod_group_id=com.cinemamod
mod_authors=CinemaMod Group
mod_description=Web browser displays for Minecraft
mod_license=All Rights Reserved
mod_credits=CinemaMod Group
# Minecraft/Forge versions # Dependencies
minecraft_version=1.20.1 forge_version=1.19.2-43.2.6
forge_version=47.3.4
minecraft_version_range=[1.20.1,1.21)
forge_version_range=[47,)
loader_version_range=[47,)
# Parchment mappings
mapping_channel=parchment
mapping_version=2023.09.03-1.20.1
mapping_lasting_version=2023.09.03
# Other mod versions
jei_version=15.20.0.112
player_anim_version=1.0.2-rc1+1.20
geckolib_version=4.2.1
curios_version=5.5.0+1.20.1

0
gradlew vendored Executable file → Normal file
View File

BIN
libs/mcef-2.x.jar Normal file

Binary file not shown.

View File

@ -1,11 +1,28 @@
pluginManagement { pluginManagement {
repositories { repositories {
mavenLocal()
gradlePluginPortal() gradlePluginPortal()
maven { url = 'https://maven.neoforged.net/releases' } maven {
name = 'NeoForged'
url = 'https://maven.neoforged.net/releases'
}
maven { url = 'https://maven.parchmentmc.org' } // Add this line maven { url = 'https://maven.parchmentmc.org' } // Add this line
} }
// resolutionStrategy {
// eachPlugin {
// switch (requested.id.toString()) {
// case "net.minecraftforge.gradle": {
// useModule("${requested.id}:ForgeGradle:${requested.version}")
// break
// }
// case "org.spongepowered.mixin": {
// useModule("org.spongepowered:mixingradle:${requested.version}")
// break;
// }
// }
// }
// }
} }
plugins { plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0' id 'org.gradle.toolchains.foojay-resolver-convention' version '0.5.0'
} }

View File

@ -14,21 +14,14 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec3; import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.server.ServerLifecycleHooks; import net.minecraftforge.server.ServerLifecycleHooks;
import net.montoyo.wd.core.HasAdvancement; import net.montoyo.wd.core.HasAdvancement;
import net.montoyo.wd.core.JSServerRequest; import net.montoyo.wd.core.JSServerRequest;
import net.montoyo.wd.data.GuiData; import net.montoyo.wd.data.GuiData;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import org.joml.Vector3d;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.UUID; import java.util.UUID;
@ -44,7 +37,7 @@ public class SharedProxy {
public void postInit() { public void postInit() {
} }
public void onCefInit() { public void onCefInit(/*CefInitEvent event*/) {
} }
@Deprecated(forRemoval = true) @Deprecated(forRemoval = true)
@ -65,7 +58,7 @@ public class SharedProxy {
Log.error("Called SharedProxy.displayGui() on server side..."); Log.error("Called SharedProxy.displayGui() on server side...");
} }
public void trackScreen(ScreenBlockEntity tes, boolean track) { public void trackScreen(TileEntityScreen tes, boolean track) {
} }
public void onAutocompleteResult(NameUUIDPair pairs[]) { public void onAutocompleteResult(NameUUIDPair pairs[]) {
@ -128,21 +121,4 @@ public class SharedProxy {
public boolean isShiftDown() { public boolean isShiftDown() {
return false; return false;
} }
public double distanceTo(ScreenBlockEntity tes, Vec3 position) {
double dist = Double.POSITIVE_INFINITY;
for (int i = 0; i < tes.screenCount(); i++) {
ScreenData scrn = tes.getScreen(i);
Vector3d pos = new Vector3d(
scrn.side.right.x * scrn.size.x / 2d + scrn.size.y * scrn.side.up.x / 2d,
scrn.side.right.y * scrn.size.x / 2d + scrn.size.y * scrn.side.up.y / 2d,
scrn.side.right.z * scrn.size.x / 2d + scrn.size.y * scrn.side.up.z / 2d
).add(tes.getBlockPos().getX(), tes.getBlockPos().getY(), tes.getBlockPos().getZ());
double dist2 = position.distanceToSqr(pos.x, pos.y, pos.z);
dist = Math.min(dist, dist2);
}
return dist;
}
} }

View File

@ -4,6 +4,8 @@
package net.montoyo.wd; package net.montoyo.wd;
import com.cinemamod.mcef.MCEF;
import com.cinemamod.mcef.MCEFBrowser;
import com.google.gson.Gson; import com.google.gson.Gson;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.advancements.Advancement; import net.minecraft.advancements.Advancement;
@ -38,21 +40,26 @@ import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.ForgeRegistries;
import net.montoyo.wd.client.ClientProxy; import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.client.gui.camera.KeyboardCamera;
import net.montoyo.wd.config.ClientConfig; import net.montoyo.wd.config.ClientConfig;
import net.montoyo.wd.config.CommonConfig; import net.montoyo.wd.config.CommonConfig;
import net.montoyo.wd.controls.ScreenControlRegistry; import net.montoyo.wd.controls.ScreenControlRegistry;
import net.montoyo.wd.core.*; import net.montoyo.wd.core.*;
import net.montoyo.wd.init.BlockInit;
import net.montoyo.wd.init.ItemInit;
import net.montoyo.wd.init.TabInit;
import net.montoyo.wd.init.TileInit;
import net.montoyo.wd.miniserv.server.Server; import net.montoyo.wd.miniserv.server.Server;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageEnableSSR;
import net.montoyo.wd.net.client_bound.S2CMessageServerInfo; import net.montoyo.wd.net.client_bound.S2CMessageServerInfo;
import net.montoyo.wd.registry.BlockRegistry; import net.montoyo.wd.remote.IWDBrowser;
import net.montoyo.wd.registry.ItemRegistry; import net.montoyo.wd.remote.client.RemoteBrowser;
import net.montoyo.wd.registry.TileRegistry; import net.montoyo.wd.remote.server.BlankBrowser;
import net.montoyo.wd.registry.WDTabs; import net.montoyo.wd.remote.server.ServerBrowser;
import net.montoyo.wd.utilities.DistSafety; import net.montoyo.wd.utilities.DistSafety;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import org.cef.browser.CefBrowser;
import java.io.*; import java.io.*;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -97,15 +104,18 @@ public class WebDisplays {
public long miniservQuota; public long miniservQuota;
public float ytVolume; public float ytVolume;
public float avDist100; public float avDist100;
public float avDist0;
public float avDist0;
// mod detection // mod detection
private boolean hasOC; private boolean hasOC;
private boolean hasCC; private boolean hasCC;
private static boolean SSR = false;
public WebDisplays() { public WebDisplays() {
INSTANCE = this; INSTANCE = this;
if(FMLEnvironment.dist.isClient()) { if (FMLEnvironment.dist.isClient()) {
PROXY = DistSafety.createProxy(); PROXY = DistSafety.createProxy();
} else { } else {
PROXY = new SharedProxy(); PROXY = new SharedProxy();
@ -115,8 +125,6 @@ public class WebDisplays {
// proxies are annoying, so from now on, I'mma be just registering stuff in here // proxies are annoying, so from now on, I'mma be just registering stuff in here
FMLJavaModLoadingContext.get().getModEventBus().addListener(ClientProxy::onKeybindRegistry); FMLJavaModLoadingContext.get().getModEventBus().addListener(ClientProxy::onKeybindRegistry);
MinecraftForge.EVENT_BUS.addListener(ClientProxy::onDrawSelection); MinecraftForge.EVENT_BUS.addListener(ClientProxy::onDrawSelection);
MinecraftForge.EVENT_BUS.addListener(KeyboardCamera::updateCamera);
MinecraftForge.EVENT_BUS.addListener(KeyboardCamera::gameTick);
ClientConfig.init(); ClientConfig.init();
} }
@ -133,10 +141,10 @@ public class WebDisplays {
WDNetworkRegistry.init(); WDNetworkRegistry.init();
SOUNDS.register(bus); SOUNDS.register(bus);
onRegisterSounds(); onRegisterSounds();
WDTabs.init(bus); TabInit.init(bus);
BlockRegistry.init(bus); BlockInit.init(bus);
ItemRegistry.init(bus); ItemInit.init(bus);
TileRegistry.init(bus); TileInit.init(bus);
PROXY.preInit(); PROXY.preInit();
@ -213,7 +221,7 @@ public class WebDisplays {
if (miniservPort != 0) { if (miniservPort != 0) {
Server sv = Server.getInstance(); Server sv = Server.getInstance();
if(!serverStartedDimensions.contains(level.dimension())) { if (!serverStartedDimensions.contains(level.dimension())) {
sv.setPort(miniservPort); sv.setPort(miniservPort);
sv.setDirectory(new File(worldDir, "wd_filehost")); sv.setDirectory(new File(worldDir, "wd_filehost"));
sv.start(); sv.start();
@ -225,7 +233,7 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onWorldLeave(LevelEvent.Unload ev) throws IOException { public void onWorldLeave(LevelEvent.Unload ev) throws IOException {
if(ev.getLevel() instanceof Level level) { if (ev.getLevel() instanceof Level level) {
if (ev.getLevel().isClientSide() || level.dimension() != Level.OVERWORLD) if (ev.getLevel().isClientSide() || level.dimension() != Level.OVERWORLD)
return; return;
Server sw = Server.getInstance(); Server sw = Server.getInstance();
@ -236,7 +244,7 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onWorldSave(LevelEvent.Save ev) { public void onWorldSave(LevelEvent.Save ev) {
if(ev.getLevel() instanceof Level level) { if (ev.getLevel() instanceof Level level) {
if (ev.getLevel().isClientSide() || level.dimension() != Level.OVERWORLD) if (ev.getLevel().isClientSide() || level.dimension() != Level.OVERWORLD)
return; return;
File f = new File(Objects.requireNonNull(ev.getLevel().getServer()).getServerDirectory(), "wd_next.txt"); File f = new File(Objects.requireNonNull(ev.getLevel().getServer()).getServerDirectory(), "wd_next.txt");
@ -253,13 +261,13 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onToss(ItemTossEvent ev) { public void onToss(ItemTossEvent ev) {
if(!ev.getEntity().level().isClientSide) { if (!ev.getEntity().level().isClientSide) {
ItemStack is = ev.getEntity().getItem(); ItemStack is = ev.getEntity().getItem();
if(is.getItem() == ItemRegistry.MINEPAD.get()) { if (is.getItem() == ItemInit.MINEPAD.get()) {
CompoundTag tag = is.getTag(); CompoundTag tag = is.getTag();
if(tag == null) { if (tag == null) {
tag = new CompoundTag(); tag = new CompoundTag();
is.setTag(tag); is.setTag(tag);
} }
@ -274,11 +282,11 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onPlayerCraft(PlayerEvent.ItemCraftedEvent ev) { public void onPlayerCraft(PlayerEvent.ItemCraftedEvent ev) {
if(CommonConfig.hardRecipes && ItemRegistry.isCompCraftItem(ev.getCrafting().getItem()) && (CraftComponent.EXTCARD.makeItemStack().is(ev.getCrafting().getItem()))) { if (CommonConfig.hardRecipes && ItemInit.isCompCraftItem(ev.getCrafting().getItem()) && (CraftComponent.EXTCARD.makeItemStack().is(ev.getCrafting().getItem()))) {
if((ev.getEntity() instanceof ServerPlayer && !hasPlayerAdvancement((ServerPlayer) ev.getEntity(), ADV_PAD_BREAK)) || PROXY.hasClientPlayerAdvancement(ADV_PAD_BREAK) != HasAdvancement.YES) { if ((ev.getEntity() instanceof ServerPlayer && !hasPlayerAdvancement((ServerPlayer) ev.getEntity(), ADV_PAD_BREAK)) || PROXY.hasClientPlayerAdvancement(ADV_PAD_BREAK) != HasAdvancement.YES) {
ev.getCrafting().setDamageValue(CraftComponent.BADEXTCARD.ordinal()); ev.getCrafting().setDamageValue(CraftComponent.BADEXTCARD.ordinal());
if(!ev.getEntity().level().isClientSide) if (!ev.getEntity().level().isClientSide)
ev.getEntity().level().playSound(null, ev.getEntity().getX(), ev.getEntity().getY(), ev.getEntity().getZ(), SoundEvents.ITEM_BREAK, SoundSource.MASTER, 1.0f, 1.0f); ev.getEntity().level().playSound(null, ev.getEntity().getX(), ev.getEntity().getY(), ev.getEntity().getZ(), SoundEvents.ITEM_BREAK, SoundSource.MASTER, 1.0f, 1.0f);
} }
} }
@ -291,14 +299,10 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onLogIn(PlayerEvent.PlayerLoggedInEvent ev) { public void onLogIn(PlayerEvent.PlayerLoggedInEvent ev) {
if (!CommonConfig.joinMessage) { if (!ev.getEntity().level().isClientSide && ev.getEntity() instanceof ServerPlayer) {
return;
}
if(!ev.getEntity().level().isClientSide && ev.getEntity() instanceof ServerPlayer) {
IWDDCapability cap = ev.getEntity().getCapability(WDDCapability.Provider.cap, null).orElseThrow(RuntimeException::new); IWDDCapability cap = ev.getEntity().getCapability(WDDCapability.Provider.cap, null).orElseThrow(RuntimeException::new);
if(cap.isFirstRun()) { if (cap.isFirstRun()) {
Util.toast(ev.getEntity(), ChatFormatting.LIGHT_PURPLE, "welcome1"); Util.toast(ev.getEntity(), ChatFormatting.LIGHT_PURPLE, "welcome1");
Util.toast(ev.getEntity(), ChatFormatting.LIGHT_PURPLE, "welcome2"); Util.toast(ev.getEntity(), ChatFormatting.LIGHT_PURPLE, "welcome2");
Util.toast(ev.getEntity(), ChatFormatting.LIGHT_PURPLE, "welcome3"); Util.toast(ev.getEntity(), ChatFormatting.LIGHT_PURPLE, "welcome3");
@ -318,27 +322,27 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onLogOut(PlayerEvent.PlayerLoggedOutEvent ev) { public void onLogOut(PlayerEvent.PlayerLoggedOutEvent ev) {
if(!ev.getEntity().level().isClientSide) if (!ev.getEntity().level().isClientSide)
Server.getInstance().getClientManager().revokeClientKey(ev.getEntity().getGameProfile().getId()); Server.getInstance().getClientManager().revokeClientKey(ev.getEntity().getGameProfile().getId());
} }
@SubscribeEvent @SubscribeEvent
public void attachEntityCaps(AttachCapabilitiesEvent<Entity> ev) { public void attachEntityCaps(AttachCapabilitiesEvent<Entity> ev) {
if(ev.getObject() instanceof Player) if (ev.getObject() instanceof Player)
ev.addCapability(CAPABILITY, new WDDCapability.Provider()); ev.addCapability(CAPABILITY, new WDDCapability.Provider());
} }
@SubscribeEvent @SubscribeEvent
public void onPlayerClone(PlayerEvent.Clone ev) { public void onPlayerClone(PlayerEvent.Clone ev) {
IWDDCapability src = ev.getOriginal().getCapability(WDDCapability.Provider.cap, null).orElse(new WDDCapability.Factory().call()); IWDDCapability src = ev.getOriginal().getCapability(WDDCapability.Provider.cap, null).orElse(new WDDCapability.Factory().call());
IWDDCapability dst = ev.getEntity().getCapability(WDDCapability.Provider.cap, null).orElse(new WDDCapability.Factory().call()); IWDDCapability dst = ev.getEntity().getCapability(WDDCapability.Provider.cap, null).orElse(new WDDCapability.Factory().call());
if(src == null) { if (src == null) {
Log.error("src is null"); Log.error("src is null");
return; return;
} }
if(dst == null) { if (dst == null) {
Log.error("dst is null"); Log.error("dst is null");
return; return;
} }
@ -350,14 +354,14 @@ public class WebDisplays {
public void onServerChat(ServerChatEvent ev) { public void onServerChat(ServerChatEvent ev) {
String msg = ev.getMessage().getString().replaceAll("\\s+", " ").toLowerCase(); String msg = ev.getMessage().getString().replaceAll("\\s+", " ").toLowerCase();
StringBuilder sb = new StringBuilder(msg.length()); StringBuilder sb = new StringBuilder(msg.length());
for(int i = 0; i < msg.length(); i++) { for (int i = 0; i < msg.length(); i++) {
char chr = msg.charAt(i); char chr = msg.charAt(i);
if(chr != '.' && chr != ',' && chr != ';' && chr != '!' && chr != '?' && chr != ':' && chr != '\'' && chr != '\"' && chr != '`') if (chr != '.' && chr != ',' && chr != ';' && chr != '!' && chr != '?' && chr != ':' && chr != '\'' && chr != '\"' && chr != '`')
sb.append(chr); sb.append(chr);
} }
if(sb.toString().equals("ironic he could save others from death but not himself")) { if (sb.toString().equals("ironic he could save others from death but not himself")) {
Player ply = ev.getPlayer(); Player ply = ev.getPlayer();
ply.level().playSound(null, ply.getX(), ply.getY(), ply.getZ(), soundIronic, SoundSource.PLAYERS, 1.0f, 1.0f); ply.level().playSound(null, ply.getX(), ply.getY(), ply.getZ(), soundIronic, SoundSource.PLAYERS, 1.0f, 1.0f);
} }
@ -365,13 +369,13 @@ public class WebDisplays {
@SubscribeEvent @SubscribeEvent
public void onClientChat(ClientChatEvent ev) { public void onClientChat(ClientChatEvent ev) {
if(ev.getMessage().equals("!WD render recipes")) if (ev.getMessage().equals("!WD render recipes"))
PROXY.renderRecipes(); PROXY.renderRecipes();
} }
private boolean hasPlayerAdvancement(ServerPlayer ply, ResourceLocation rl) { private boolean hasPlayerAdvancement(ServerPlayer ply, ResourceLocation rl) {
MinecraftServer server = PROXY.getServer(); MinecraftServer server = PROXY.getServer();
if(server == null) if (server == null)
return false; return false;
Advancement adv = server.getAdvancements().getAdvancement(rl); Advancement adv = server.getAdvancements().getAdvancement(rl);
@ -392,18 +396,18 @@ public class WebDisplays {
return ret; return ret;
} }
private static void registerTrigger(Criterion ... criteria) { private static void registerTrigger(Criterion... criteria) {
for(Criterion c: criteria) for (Criterion c : criteria)
CriteriaTriggers.register(c); CriteriaTriggers.register(c);
} }
// public static boolean isOpenComputersAvailable() { // public static boolean isOpenComputersAvailable() {
// return INSTANCE.hasOC; // return INSTANCE.hasOC;
// } // }
// public static boolean isComputerCraftAvailable() { // public static boolean isComputerCraftAvailable() {
// return INSTANCE.hasCC; // return INSTANCE.hasCC;
// } // }
public static boolean isSiteBlacklisted(String url) { public static boolean isSiteBlacklisted(String url) {
try { try {
@ -411,7 +415,7 @@ public class WebDisplays {
for (String str : CommonConfig.Browser.blacklist) for (String str : CommonConfig.Browser.blacklist)
if (str.equalsIgnoreCase(url2.getHost())) return true; if (str.equalsIgnoreCase(url2.getHost())) return true;
return false; return false;
} catch(MalformedURLException ex) { } catch (MalformedURLException ex) {
return false; return false;
} }
} }
@ -419,5 +423,20 @@ public class WebDisplays {
public static String applyBlacklist(String url) { public static String applyBlacklist(String url) {
return isSiteBlacklisted(url) ? BLACKLIST_URL : url; return isSiteBlacklisted(url) ? BLACKLIST_URL : url;
} }
}
public static boolean isSSR() {
return SSR;
}
public static void markSSR() {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
StackTraceElement caller = elements[3];
try {
Class<?> c = Class.forName(caller.getClassName());
if (c == S2CMessageEnableSSR.class || c == WebDisplays.class) {
SSR = true;
}
} catch (Throwable err) {
}
}
}

View File

@ -26,13 +26,14 @@ import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.PacketDistributor;
import net.montoyo.wd.core.DefaultPeripheral; import net.montoyo.wd.core.DefaultPeripheral;
import net.montoyo.wd.entity.KeyboardBlockEntity; import net.montoyo.wd.entity.TileEntityKeyboard;
import net.montoyo.wd.item.ItemLinker; import net.montoyo.wd.item.ItemLinker;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageCloseGui; import net.montoyo.wd.net.client_bound.S2CMessageCloseGui;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class KeyboardBlockLeft extends PeripheralBlock { public class BlockKeyboardLeft extends BlockPeripheral {
public static final EnumProperty<DefaultPeripheral> TYPE = EnumProperty.create("type", DefaultPeripheral.class); public static final EnumProperty<DefaultPeripheral> TYPE = EnumProperty.create("type", DefaultPeripheral.class);
public static final DirectionProperty FACING = DirectionProperty.create("facing", Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST); public static final DirectionProperty FACING = DirectionProperty.create("facing", Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST);
// public static final DirectionProperty HALF = DirectionProperty.create("facing", Direction.EAST, Direction.WEST); // public static final DirectionProperty HALF = DirectionProperty.create("facing", Direction.EAST, Direction.WEST);
@ -46,25 +47,25 @@ public class KeyboardBlockLeft extends PeripheralBlock {
private static final Property<?>[] properties = new Property<?>[] {TYPE, FACING}; private static final Property<?>[] properties = new Property<?>[] {TYPE, FACING};
public KeyboardBlockLeft() { public BlockKeyboardLeft() {
super(DefaultPeripheral.KEYBOARD); super(DefaultPeripheral.KEYBOARD);
} }
// TODO: make non static (for extensibility purposes) // TODO: make non static (for extensibility purposes)
public static KeyboardBlockEntity getTileEntity(BlockState state, Level world, BlockPos pos) { public static TileEntityKeyboard getTileEntity(BlockState state, Level world, BlockPos pos) {
if (state.getBlock() instanceof KeyboardBlockLeft) { if (state.getBlock() instanceof BlockKeyboardLeft) {
BlockEntity te = world.getBlockEntity(pos); // TODO: check? BlockEntity te = world.getBlockEntity(pos); // TODO: check?
if (te instanceof KeyboardBlockEntity) if (te instanceof TileEntityKeyboard)
return (KeyboardBlockEntity) te; return (TileEntityKeyboard) te;
} }
BlockPos relative = pos.relative(KeyboardBlockLeft.mapDirection(state.getValue(FACING).getOpposite())); BlockPos relative = pos.relative(BlockKeyboardLeft.mapDirection(state.getValue(FACING).getOpposite()));
BlockState ns = world.getBlockState(relative); BlockState ns = world.getBlockState(relative);
if (ns.getBlock() instanceof PeripheralBlock) { if (ns.getBlock() instanceof BlockPeripheral) {
BlockEntity te = world.getBlockEntity(relative); // TODO: check? BlockEntity te = world.getBlockEntity(relative); // TODO: check?
if (te instanceof KeyboardBlockEntity) if (te instanceof TileEntityKeyboard)
return (KeyboardBlockEntity) te; return (TileEntityKeyboard) te;
} }
return null; return null;
@ -89,7 +90,7 @@ public class KeyboardBlockLeft extends PeripheralBlock {
public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) {
double rpos = (entity.getY() - ((double) pos.getY())) * 16.0; double rpos = (entity.getY() - ((double) pos.getY())) * 16.0;
if (!world.isClientSide && rpos >= 1.0 && rpos <= 2.0 && Math.random() < 0.25) { if (!world.isClientSide && rpos >= 1.0 && rpos <= 2.0 && Math.random() < 0.25) {
KeyboardBlockEntity tek = KeyboardBlockLeft.getTileEntity(state, world, pos); TileEntityKeyboard tek = BlockKeyboardLeft.getTileEntity(state, world, pos);
if (tek != null) if (tek != null)
tek.simulateCat(entity); tek.simulateCat(entity);
@ -101,7 +102,7 @@ public class KeyboardBlockLeft extends PeripheralBlock {
if (player.getItemInHand(hand).getItem() instanceof ItemLinker) if (player.getItemInHand(hand).getItem() instanceof ItemLinker)
return InteractionResult.PASS; return InteractionResult.PASS;
KeyboardBlockEntity tek = KeyboardBlockLeft.getTileEntity(state, level, pos); TileEntityKeyboard tek = BlockKeyboardLeft.getTileEntity(state, level, pos);
if (tek != null) if (tek != null)
return tek.onRightClick(player, hand); return tek.onRightClick(player, hand);
@ -119,10 +120,10 @@ public class KeyboardBlockLeft extends PeripheralBlock {
} }
private static void removeRightPiece(BlockState state, Level world, BlockPos pos) { private static void removeRightPiece(BlockState state, Level world, BlockPos pos) {
BlockPos relative = pos.relative(KeyboardBlockLeft.mapDirection(state.getValue(FACING))); BlockPos relative = pos.relative(BlockKeyboardLeft.mapDirection(state.getValue(FACING)));
BlockState ns = world.getBlockState(relative); BlockState ns = world.getBlockState(relative);
if (ns.getBlock() instanceof KeyboardBlockRight) if (ns.getBlock() instanceof BlockKeyboardRight)
world.setBlock(relative, Blocks.AIR.defaultBlockState(), 3); world.setBlock(relative, Blocks.AIR.defaultBlockState(), 3);
} }

View File

@ -23,31 +23,32 @@ import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.PacketDistributor;
import net.montoyo.wd.core.IPeripheral; import net.montoyo.wd.core.IPeripheral;
import net.montoyo.wd.entity.KeyboardBlockEntity; import net.montoyo.wd.entity.TileEntityKeyboard;
import net.montoyo.wd.item.ItemLinker; import net.montoyo.wd.item.ItemLinker;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageCloseGui; import net.montoyo.wd.net.client_bound.S2CMessageCloseGui;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import static net.montoyo.wd.block.KeyboardBlockLeft.KEYBOARD_AABBS; import static net.montoyo.wd.block.BlockKeyboardLeft.KEYBOARD_AABBS;
import static net.montoyo.wd.block.PeripheralBlock.point; import static net.montoyo.wd.block.BlockPeripheral.point;
// TODO: merge into KeyboardLeft // TODO: merge into KeyboardLeft
public class KeyboardBlockRight extends Block implements IPeripheral { public class BlockKeyboardRight extends Block implements IPeripheral {
public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING; public static final DirectionProperty FACING = BlockStateProperties.HORIZONTAL_FACING;
public KeyboardBlockRight() { public BlockKeyboardRight() {
super(Properties.copy(Blocks.STONE) super(Properties.copy(Blocks.STONE)
.strength(1.5f, 10.f)); .strength(1.5f, 10.f));
} }
private static void removeLeftPiece(BlockState state, Level world, BlockPos pos) { private static void removeLeftPiece(BlockState state, Level world, BlockPos pos) {
BlockPos relative = pos.relative(KeyboardBlockLeft.mapDirection(state.getValue(FACING).getOpposite())); BlockPos relative = pos.relative(BlockKeyboardLeft.mapDirection(state.getValue(FACING).getOpposite()));
BlockState ns = world.getBlockState(relative); BlockState ns = world.getBlockState(relative);
if (ns.getBlock() instanceof KeyboardBlockLeft) if (ns.getBlock() instanceof BlockKeyboardLeft)
world.setBlock(relative, Blocks.AIR.defaultBlockState(), 3); world.setBlock(relative, Blocks.AIR.defaultBlockState(), 3);
} }
@ -82,7 +83,7 @@ public class KeyboardBlockRight extends Block implements IPeripheral {
@Override @Override
public boolean connect(Level world, BlockPos pos, BlockState state, Vector3i scrPos, BlockSide scrSide) { public boolean connect(Level world, BlockPos pos, BlockState state, Vector3i scrPos, BlockSide scrSide) {
KeyboardBlockEntity keyboard = KeyboardBlockLeft.getTileEntity(state, world, pos); TileEntityKeyboard keyboard = BlockKeyboardLeft.getTileEntity(state, world, pos);
return keyboard != null && keyboard.connect(world, pos, state, scrPos, scrSide); return keyboard != null && keyboard.connect(world, pos, state, scrPos, scrSide);
} }
@ -90,7 +91,7 @@ public class KeyboardBlockRight extends Block implements IPeripheral {
public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) { public void entityInside(BlockState state, Level world, BlockPos pos, Entity entity) {
double rpos = (entity.getY() - ((double) pos.getY())) * 16.0; double rpos = (entity.getY() - ((double) pos.getY())) * 16.0;
if (!world.isClientSide && rpos >= 1.0 && rpos <= 2.0 && Math.random() < 0.25) { if (!world.isClientSide && rpos >= 1.0 && rpos <= 2.0 && Math.random() < 0.25) {
KeyboardBlockEntity tek = KeyboardBlockLeft.getTileEntity(state, world, pos); TileEntityKeyboard tek = BlockKeyboardLeft.getTileEntity(state, world, pos);
if (tek != null) if (tek != null)
tek.simulateCat(entity); tek.simulateCat(entity);
@ -102,7 +103,7 @@ public class KeyboardBlockRight extends Block implements IPeripheral {
if (player.getItemInHand(hand).getItem() instanceof ItemLinker) if (player.getItemInHand(hand).getItem() instanceof ItemLinker)
return InteractionResult.PASS; return InteractionResult.PASS;
KeyboardBlockEntity tek = KeyboardBlockLeft.getTileEntity(state, level, pos); TileEntityKeyboard tek = BlockKeyboardLeft.getTileEntity(state, level, pos);
if (tek != null) if (tek != null)
return tek.onRightClick(player, hand); return tek.onRightClick(player, hand);

View File

@ -28,19 +28,19 @@ import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; import net.minecraft.world.phys.shapes.VoxelShape;
import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.PacketDistributor;
import net.montoyo.wd.core.DefaultPeripheral; import net.montoyo.wd.core.DefaultPeripheral;
import net.montoyo.wd.entity.AbstractInterfaceBlockEntity; import net.montoyo.wd.entity.TileEntityInterfaceBase;
import net.montoyo.wd.entity.AbstractPeripheralBlockEntity; import net.montoyo.wd.entity.TileEntityPeripheralBase;
import net.montoyo.wd.entity.ServerBlockEntity; import net.montoyo.wd.entity.TileEntityServer;
import net.montoyo.wd.item.ItemLinker; import net.montoyo.wd.item.ItemLinker;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageCloseGui; import net.montoyo.wd.net.client_bound.S2CMessageCloseGui;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
public class PeripheralBlock extends WDContainerBlock { public class BlockPeripheral extends WDBlockContainer {
DefaultPeripheral type; DefaultPeripheral type;
public PeripheralBlock(DefaultPeripheral type) { public BlockPeripheral(DefaultPeripheral type) {
super(BlockBehaviour.Properties.copy(Blocks.STONE).strength(1.5f, 10.f)); super(BlockBehaviour.Properties.copy(Blocks.STONE).strength(1.5f, 10.f));
this.type = type; this.type = type;
} }
@ -49,12 +49,12 @@ public class PeripheralBlock extends WDContainerBlock {
@Override @Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) { public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
BlockEntityType.BlockEntitySupplier<? extends BlockEntity> cls = type.getTEClass(); BlockEntityType.BlockEntitySupplier<? extends BlockEntity> cls = type.getTEClass();
if (cls == null) if(cls == null)
return null; return null;
try { try {
return cls.create(pos, state); return cls.create(pos, state);
} catch (Throwable t) { } catch(Throwable t) {
Log.errorEx("Couldn't instantiate peripheral TileEntity:", t); Log.errorEx("Couldn't instantiate peripheral TileEntity:", t);
} }
@ -68,18 +68,18 @@ public class PeripheralBlock extends WDContainerBlock {
@Override @Override
public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
if (player.isShiftKeyDown()) if(player.isShiftKeyDown())
return InteractionResult.FAIL; return InteractionResult.FAIL;
if (player.getItemInHand(hand).getItem() instanceof ItemLinker) if(player.getItemInHand(hand).getItem() instanceof ItemLinker)
return InteractionResult.FAIL; return InteractionResult.FAIL;
BlockEntity te = world.getBlockEntity(pos); BlockEntity te = world.getBlockEntity(pos);
if (te instanceof AbstractPeripheralBlockEntity) if(te instanceof TileEntityPeripheralBase)
return ((AbstractPeripheralBlockEntity) te).onRightClick(player, hand); return ((TileEntityPeripheralBase) te).onRightClick(player, hand);
else if (te instanceof ServerBlockEntity) { else if(te instanceof TileEntityServer) {
((ServerBlockEntity) te).onPlayerRightClick(player); ((TileEntityServer) te).onPlayerRightClick(player);
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} else } else
return InteractionResult.FAIL; return InteractionResult.FAIL;
@ -92,16 +92,16 @@ public class PeripheralBlock extends WDContainerBlock {
@Override @Override
public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) { public void setPlacedBy(Level world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) {
if (world.isClientSide) if(world.isClientSide)
return; return;
if (placer instanceof Player) { if(placer instanceof Player) {
BlockEntity te = world.getBlockEntity(pos); BlockEntity te = world.getBlockEntity(pos);
if (te instanceof ServerBlockEntity) if(te instanceof TileEntityServer)
((ServerBlockEntity) te).setOwner((Player) placer); ((TileEntityServer) te).setOwner((Player) placer);
else if (te instanceof AbstractInterfaceBlockEntity) else if(te instanceof TileEntityInterfaceBase)
((AbstractInterfaceBlockEntity) te).setOwner((Player) placer); ((TileEntityInterfaceBase) te).setOwner((Player) placer);
} }
} }
@ -113,13 +113,13 @@ public class PeripheralBlock extends WDContainerBlock {
@Override @Override
public void neighborChanged(BlockState state, Level world, BlockPos pos, Block neighborType, BlockPos neighbor, boolean isMoving) { public void neighborChanged(BlockState state, Level world, BlockPos pos, Block neighborType, BlockPos neighbor, boolean isMoving) {
BlockEntity te = world.getBlockEntity(pos); BlockEntity te = world.getBlockEntity(pos);
if (te instanceof AbstractPeripheralBlockEntity) if(te instanceof TileEntityPeripheralBase)
((AbstractPeripheralBlockEntity) te).onNeighborChange(neighborType, neighbor); ((TileEntityPeripheralBase) te).onNeighborChange(neighborType, neighbor);
} }
@Override @Override
public void playerDestroy(Level world, Player player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack tool) { public void playerDestroy(Level world, Player player, BlockPos pos, BlockState state, @Nullable BlockEntity blockEntity, ItemStack tool) {
if (!world.isClientSide) { if(!world.isClientSide) {
WDNetworkRegistry.INSTANCE.send(PacketDistributor.NEAR.with(() -> point(world, pos)), new S2CMessageCloseGui(pos)); WDNetworkRegistry.INSTANCE.send(PacketDistributor.NEAR.with(() -> point(world, pos)), new S2CMessageCloseGui(pos));
} }
super.playerDestroy(world, player, pos, state, blockEntity, tool); super.playerDestroy(world, player, pos, state, blockEntity, tool);

View File

@ -13,8 +13,10 @@ import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.RenderShape;
@ -32,27 +34,59 @@ import net.montoyo.wd.core.DefaultUpgrade;
import net.montoyo.wd.core.IUpgrade; import net.montoyo.wd.core.IUpgrade;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.data.SetURLData; import net.montoyo.wd.data.SetURLData;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.init.BlockInit;
import net.montoyo.wd.item.ItemLaserPointer; import net.montoyo.wd.item.ItemLaserPointer;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.math.Vector3f;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.serialization.Util;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class ScreenBlock extends BaseEntityBlock { public class BlockScreen extends BaseEntityBlock {
public static final BooleanProperty hasTE = BooleanProperty.create("haste"); public static final BooleanProperty hasTE = BooleanProperty.create("haste");
public static final BooleanProperty emitting = BooleanProperty.create("emitting"); public static final BooleanProperty emitting = BooleanProperty.create("emitting");
private static final Property<?>[] properties = new Property<?>[]{hasTE, emitting}; private static final Property<?>[] properties = new Property<?>[]{hasTE, emitting};
public ScreenBlock(Properties properties) { public BlockScreen(Properties properties) {
super(properties.strength(1.5f, 10.f)); super(properties.strength(1.5f, 10.f));
this.registerDefaultState(this.defaultBlockState().setValue(hasTE, false).setValue(emitting, false)); this.registerDefaultState(this.defaultBlockState().setValue(hasTE, false).setValue(emitting, false));
} }
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(properties);
}
@Override
public RenderShape getRenderShape(BlockState state) {
return RenderShape.MODEL;
}
public static boolean isntScreenBlock(Level world, Vector3i pos) {
return world.getBlockState(pos.toBlock()).getBlock() != BlockInit.blockScreen.get();
}
@org.jetbrains.annotations.Nullable
@Override
public BlockState getStateForPlacement(BlockPlaceContext context) {
return super.getStateForPlacement(context);
}
@Override
public BlockState updateShape(BlockState state, Direction direction, BlockState neighborState, LevelAccessor level, BlockPos currentPos, BlockPos neighborPos) {
return super.updateShape(state, direction, neighborState, level, currentPos, neighborPos);
}
public int getMetaFromState(BlockState state) {
int ret = 0;
if (state.getValue(hasTE))
ret |= 1;
if (state.getValue(emitting))
ret |= 2;
return ret;
}
@Override @Override
public void onRemove(BlockState p_60515_, Level p_60516_, BlockPos p_60517_, BlockState p_60518_, boolean p_60519_) { public void onRemove(BlockState p_60515_, Level p_60516_, BlockPos p_60517_, BlockState p_60518_, boolean p_60519_) {
// TODO: make this also get called on client? // TODO: make this also get called on client?
@ -98,13 +132,13 @@ public class ScreenBlock extends BaseEntityBlock {
BlockSide side = BlockSide.values()[hit.getDirection().ordinal()]; BlockSide side = BlockSide.values()[hit.getDirection().ordinal()];
Multiblock.findOrigin(world, pos, side, null); Multiblock.findOrigin(world, pos, side, null);
ScreenBlockEntity te = (ScreenBlockEntity) world.getBlockEntity(pos.toBlock()); TileEntityScreen te = (TileEntityScreen) world.getBlockEntity(pos.toBlock());
if (te != null && te.getScreen(side) != null) { if (te != null && te.getScreen(side) != null) {
ScreenData scr = te.getScreen(side); TileEntityScreen.Screen scr = te.getScreen(side);
if (sneaking) { //Right Click if (sneaking) { //Right Click
if ((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0)
Util.toast(player, "restrictions"); Util.toast(player, "restrictions");
else else
(new SetURLData(pos, scr.side, scr.url)).sendTo((ServerPlayer) player); (new SetURLData(pos, scr.side, scr.url)).sendTo((ServerPlayer) player);
@ -174,7 +208,7 @@ public class ScreenBlock extends BaseEntityBlock {
if (te == null) { if (te == null) {
BlockPos bp = pos.toBlock(); BlockPos bp = pos.toBlock();
world.setBlockAndUpdate(bp, world.getBlockState(bp).setValue(hasTE, true)); world.setBlockAndUpdate(bp, world.getBlockState(bp).setValue(hasTE, true));
te = (ScreenBlockEntity) world.getBlockEntity(bp); te = (TileEntityScreen) world.getBlockEntity(bp);
created = true; created = true;
} }
@ -184,13 +218,13 @@ public class ScreenBlock extends BaseEntityBlock {
@Override @Override
public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos source, public void neighborChanged(BlockState state, Level world, BlockPos pos, Block block, BlockPos source,
boolean isMoving) { boolean isMoving){
if (block != this && !world.isClientSide && !state.getValue(emitting)) { if (block != this && !world.isClientSide && !state.getValue(emitting)) {
for (BlockSide side : BlockSide.values()) { for (BlockSide side : BlockSide.values()) {
Vector3i vec = new Vector3i(pos); Vector3i vec = new Vector3i(pos);
Multiblock.findOrigin(world, vec, side, null); Multiblock.findOrigin(world, vec, side, null);
ScreenBlockEntity tes = (ScreenBlockEntity) world.getBlockEntity(vec.toBlock()); TileEntityScreen tes = (TileEntityScreen) world.getBlockEntity(vec.toBlock());
if (tes != null && tes.hasUpgrade(side, DefaultUpgrade.REDINPUT)) { if (tes != null && tes.hasUpgrade(side, DefaultUpgrade.REDINPUT)) {
Direction facing = Direction.from2DDataValue(side.reverse().ordinal()); //Opposite face Direction facing = Direction.from2DDataValue(side.reverse().ordinal()); //Opposite face
vec.sub(pos.getX(), pos.getY(), pos.getZ()).neg(); vec.sub(pos.getX(), pos.getY(), pos.getZ()).neg();
@ -200,16 +234,17 @@ public class ScreenBlock extends BaseEntityBlock {
} }
} }
public static boolean hit2pixels(BlockSide side, BlockPos bpos, Vector3i pos, ScreenData scr, float hitX, float hitY, float hitZ, Vector2i dst) { public static boolean hit2pixels(BlockSide side, BlockPos bpos, Vector3i pos, TileEntityScreen.Screen scr, float hitX, float hitY, float hitZ, Vector2i dst) {
if(side.right.x < 0) if(side.right.x < 0)
hitX -= 1.f; hitX -= 1.f;
if(side.right.z < 0 || side == BlockSide.TOP || side == BlockSide.BOTTOM) if(side.right.z < 0 || side == BlockSide.TOP || side == BlockSide.BOTTOM)
hitZ -= 1.f; hitZ -= 1.f;
Vector3f rel = new Vector3f(hitX, hitY, hitZ); Vector3f rel = new Vector3f(bpos.getX(), bpos.getY(), bpos.getZ());
rel.sub((float) pos.x, (float) pos.y, (float) pos.z);
rel.add(hitX, hitY, hitZ);
// this dot is acting as a "get distance from plane" where the plane is the edge of the screen
float cx = rel.dot(side.right.toFloat()) - 2.f / 16.f; float cx = rel.dot(side.right.toFloat()) - 2.f / 16.f;
float cy = rel.dot(side.up.toFloat()) - 2.f / 16.f; float cy = rel.dot(side.up.toFloat()) - 2.f / 16.f;
float sw = ((float) scr.size.x) - 4.f / 16.f; float sw = ((float) scr.size.x) - 4.f / 16.f;
@ -218,11 +253,11 @@ public class ScreenBlock extends BaseEntityBlock {
cx /= sw; cx /= sw;
cy /= sh; cy /= sh;
if (cx >= 0.f && cx <= 1.0 && cy >= 0.f && cy <= 1.f) { if(cx >= 0.f && cx <= 1.0 && cy >= 0.f && cy <= 1.f) {
if (side != BlockSide.BOTTOM) if(side != BlockSide.BOTTOM)
cy = 1.f - cy; cy = 1.f - cy;
switch (scr.rotation) { switch(scr.rotation) {
case ROT_90: case ROT_90:
cy = 1.0f - cy; cy = 1.0f - cy;
break; break;
@ -235,12 +270,15 @@ public class ScreenBlock extends BaseEntityBlock {
case ROT_270: case ROT_270:
cx = 1.0f - cx; cx = 1.0f - cx;
break; break;
default:
break;
} }
cx *= (float) scr.resolution.x; cx *= (float) scr.resolution.x;
cy *= (float) scr.resolution.y; cy *= (float) scr.resolution.y;
if (scr.rotation.isVertical) { if(scr.rotation.isVertical) {
dst.x = (int) cy; dst.x = (int) cy;
dst.y = (int) cx; dst.y = (int) cx;
} else { } else {
@ -254,9 +292,20 @@ public class ScreenBlock extends BaseEntityBlock {
return false; return false;
} }
@org.jetbrains.annotations.Nullable
@Override
public BlockEntity newBlockEntity (BlockPos pos, BlockState state){
int meta = getMetaFromState(state);
if ((meta & 1) == 0)
return null;
return ((meta & 1) == 0) ? null : new TileEntityScreen(pos, state);
}
/************************************************* DESTRUCTION HANDLING *************************************************/ /************************************************* DESTRUCTION HANDLING *************************************************/
private void onDestroy(Level world, BlockPos pos, Player ply) { private void onDestroy (Level world, BlockPos pos, Player ply){
if (!world.isClientSide) { if (!world.isClientSide) {
Vector3i bp = new Vector3i(pos); Vector3i bp = new Vector3i(pos);
Multiblock.BlockOverride override = new Multiblock.BlockOverride(bp, Multiblock.OverrideAction.SIMULATE); Multiblock.BlockOverride override = new Multiblock.BlockOverride(bp, Multiblock.OverrideAction.SIMULATE);
@ -266,28 +315,28 @@ public class ScreenBlock extends BaseEntityBlock {
} }
} }
private void destroySide(Level world, Vector3i pos, BlockSide side, Multiblock.BlockOverride override, Player private void destroySide (Level world, Vector3i pos, BlockSide side, Multiblock.BlockOverride override, Player
source) { source){
Multiblock.findOrigin(world, pos, side, override); Multiblock.findOrigin(world, pos, side, override);
BlockPos bp = pos.toBlock(); BlockPos bp = pos.toBlock();
BlockEntity te = world.getBlockEntity(bp); BlockEntity te = world.getBlockEntity(bp);
if (te instanceof ScreenBlockEntity) { if (te instanceof TileEntityScreen) {
((ScreenBlockEntity) te).onDestroy(source); ((TileEntityScreen) te).onDestroy(source);
world.setBlock(bp, world.getBlockState(bp).setValue(hasTE, false), Block.UPDATE_ALL_IMMEDIATE); //Destroy tile entity. world.setBlock(bp, world.getBlockState(bp).setValue(hasTE, false), Block.UPDATE_ALL_IMMEDIATE); //Destroy tile entity.
} }
} }
@Override @Override
public boolean onDestroyedByPlayer(BlockState state, Level level, BlockPos pos, Player player, public boolean onDestroyedByPlayer (BlockState state, Level level, BlockPos pos, Player player,
boolean willHarvest, FluidState fluid) { boolean willHarvest, FluidState fluid){
onDestroy(level, pos, player); onDestroy(level, pos, player);
return super.onDestroyedByPlayer(state, level, pos, player, willHarvest, fluid); return super.onDestroyedByPlayer(state, level, pos, player, willHarvest, fluid);
} }
@Override @Override
public void setPlacedBy(Level world, @NotNull BlockPos pos, @NotNull BlockState public void setPlacedBy (Level world, @NotNull BlockPos pos, @NotNull BlockState
state, @org.jetbrains.annotations.Nullable LivingEntity whoDidThisShit, @NotNull ItemStack stack) { state, @org.jetbrains.annotations.Nullable LivingEntity whoDidThisShit, @NotNull ItemStack stack){
if (world.isClientSide) if (world.isClientSide)
return; return;
@ -302,42 +351,25 @@ public class ScreenBlock extends BaseEntityBlock {
neighbors[5] = new Vector3i(pos.getX(), pos.getY(), pos.getZ() - 1); neighbors[5] = new Vector3i(pos.getX(), pos.getY(), pos.getZ() - 1);
for (Vector3i neighbor : neighbors) { for (Vector3i neighbor : neighbors) {
if (world.getBlockState(neighbor.toBlock()).getBlock() instanceof ScreenBlock) { if (world.getBlockState(neighbor.toBlock()).getBlock() instanceof BlockScreen) {
for (BlockSide bs : BlockSide.values()) for (BlockSide bs : BlockSide.values())
destroySide(world, neighbor.clone(), bs, override, (whoDidThisShit instanceof Player) ? ((Player) whoDidThisShit) : null); destroySide(world, neighbor.clone(), bs, override, (whoDidThisShit instanceof Player) ? ((Player) whoDidThisShit) : null);
} }
} }
} }
/************************************************* STUFF THAT'S UNLIKELY TO BE TOUCHED BUT NEEDS TO BE HERE *************************************************/
@Override @Override
public @NotNull PushReaction getPistonPushReaction(BlockState state) { public @NotNull PushReaction getPistonPushReaction (BlockState state){
return PushReaction.IGNORE; return PushReaction.IGNORE;
} }
@Override @Override
public int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) { public int getSignal (BlockState state, BlockGetter level, BlockPos pos, Direction direction){
return state.getValue(emitting) ? 15 : 0; return state.getValue(emitting) ? 15 : 0;
} }
@Override @Override
public boolean isSignalSource(BlockState state) { public boolean isSignalSource (BlockState state){
return state.getValue(emitting); return state.getValue(emitting);
} }
@Override
public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
return state.getValue(hasTE) ? new ScreenBlockEntity(pos, state) : null;
}
@Override
public RenderShape getRenderShape(BlockState state) {
return RenderShape.MODEL;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
builder.add(properties);
}
} }

View File

@ -7,11 +7,11 @@ package net.montoyo.wd.block;
import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.BlockItem;
import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.BaseEntityBlock;
public abstract class WDContainerBlock extends BaseEntityBlock { public abstract class WDBlockContainer extends BaseEntityBlock {
protected static BlockItem itemBlock; protected static BlockItem itemBlock;
public WDContainerBlock(Properties arg) { public WDBlockContainer(Properties arg) {
super(arg); super(arg);
} }

View File

@ -7,48 +7,48 @@ import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.block.KeyboardBlockLeft; import net.montoyo.wd.block.BlockKeyboardLeft;
import net.montoyo.wd.registry.BlockRegistry; import net.montoyo.wd.init.BlockInit;
public class KeyboardItem extends BlockItem { public class KeyboardItem extends BlockItem {
public KeyboardItem(Block arg, Properties arg2) { public KeyboardItem(Block arg, Properties arg2) {
super(arg, arg2); super(arg, arg2);
} }
@Override @Override
protected boolean placeBlock(BlockPlaceContext arg, BlockState arg2) { protected boolean placeBlock(BlockPlaceContext arg, BlockState arg2) {
Direction facing = arg.getHorizontalDirection(); Direction facing = arg.getHorizontalDirection();
arg2 = arg2.setValue(KeyboardBlockLeft.FACING, facing); arg2 = arg2.setValue(BlockKeyboardLeft.FACING, facing);
Direction d = KeyboardBlockLeft.mapDirection(facing); Direction d = BlockKeyboardLeft.mapDirection(facing);
if (isValid(arg.getClickedPos(), arg.getLevel(), arg2, d)) { if (isValid(arg.getClickedPos(), arg.getLevel(), arg2, d)) {
Block kbRight = BlockRegistry.blockKbRight.get(); Block kbRight = BlockInit.blockKbRight.get();
BlockState rightState = kbRight.defaultBlockState(); BlockState rightState = kbRight.defaultBlockState();
rightState = rightState.setValue(KeyboardBlockLeft.FACING, facing); rightState = rightState.setValue(BlockKeyboardLeft.FACING, facing);
if (!arg.getLevel().setBlock( if (!arg.getLevel().setBlock(
arg.getClickedPos().relative(d), arg.getClickedPos().relative(d),
rightState, rightState,
11 11
)) return false; )) return false;
return arg.getLevel().setBlock(arg.getClickedPos(), arg2, 11);// 161 return arg.getLevel().setBlock(arg.getClickedPos(), arg2, 11);// 161
} else if (isValid(arg.getClickedPos().relative(d.getOpposite(), 2), arg.getLevel(), arg2, d)) { } else if (isValid(arg.getClickedPos().relative(d.getOpposite(), 2), arg.getLevel(), arg2, d)) {
Block kbRight = BlockRegistry.blockKbRight.get(); Block kbRight = BlockInit.blockKbRight.get();
BlockState rightState = kbRight.defaultBlockState(); BlockState rightState = kbRight.defaultBlockState();
rightState = rightState.setValue(KeyboardBlockLeft.FACING, facing); rightState = rightState.setValue(BlockKeyboardLeft.FACING, facing);
if (!arg.getLevel().setBlock( if (!arg.getLevel().setBlock(
arg.getClickedPos(), arg.getClickedPos(),
rightState, rightState,
11 11
)) return false; )) return false;
return arg.getLevel().setBlock(arg.getClickedPos().relative(d.getOpposite()), arg2, 11);// 161 return arg.getLevel().setBlock(arg.getClickedPos().relative(d.getOpposite()), arg2, 11);// 161
} }
return false; return false;
} }
private boolean isValid(BlockPos pos, Level level, BlockState state, Direction d) { private boolean isValid(BlockPos pos, Level level, BlockState state, Direction d) {
return level.getBlockState(pos.relative(d)).isAir(); return level.getBlockState(pos.relative(d)).isAir();
} }
} }

View File

@ -10,18 +10,22 @@ import com.mojang.authlib.GameProfile;
import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.advancements.Advancement; import net.minecraft.advancements.Advancement;
import net.minecraft.advancements.AdvancementProgress; import net.minecraft.advancements.AdvancementProgress;
import net.minecraft.client.Camera;
import net.minecraft.client.KeyMapping; import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.Options; import net.minecraft.client.Options;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.multiplayer.ClientAdvancements; import net.minecraft.client.multiplayer.ClientAdvancements;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import net.minecraft.client.renderer.entity.EntityRenderDispatcher; import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.resources.model.Material;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList; import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
@ -32,7 +36,6 @@ import net.minecraft.server.packs.resources.ReloadableResourceManager;
import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceManagerReloadListener; import net.minecraft.server.packs.resources.ResourceManagerReloadListener;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.HumanoidArm; import net.minecraft.world.entity.HumanoidArm;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.Slot; import net.minecraft.world.inventory.Slot;
@ -41,16 +44,14 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockGetter; import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ModelEvent; import net.minecraftforge.client.event.*;
import net.minecraftforge.client.event.RegisterKeyMappingsEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderHighlightEvent;
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.level.LevelEvent; import net.minecraftforge.event.level.LevelEvent;
@ -61,34 +62,32 @@ import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.SharedProxy; import net.montoyo.wd.SharedProxy;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.block.ScreenBlock; import net.montoyo.wd.block.BlockScreen;
import net.montoyo.wd.client.gui.*; import net.montoyo.wd.client.gui.*;
import net.montoyo.wd.client.gui.loading.GuiLoader; import net.montoyo.wd.client.gui.loading.GuiLoader;
import net.montoyo.wd.client.renderers.*; import net.montoyo.wd.client.renderers.*;
import net.montoyo.wd.config.ClientConfig;
import net.montoyo.wd.core.HasAdvancement; import net.montoyo.wd.core.HasAdvancement;
import net.montoyo.wd.core.JSServerRequest;
import net.montoyo.wd.data.GuiData; import net.montoyo.wd.data.GuiData;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.init.BlockInit;
import net.montoyo.wd.init.ItemInit;
import net.montoyo.wd.init.TileInit;
import net.montoyo.wd.item.ItemLaserPointer; import net.montoyo.wd.item.ItemLaserPointer;
import net.montoyo.wd.item.ItemMinePad2; import net.montoyo.wd.item.ItemMinePad2;
import net.montoyo.wd.item.WDItem; import net.montoyo.wd.item.WDItem;
import net.montoyo.wd.miniserv.client.Client; import net.montoyo.wd.miniserv.client.Client;
import net.montoyo.wd.registry.BlockRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.registry.ItemRegistry; import net.montoyo.wd.net.server_bound.C2SMessageMinepadUrl;
import net.montoyo.wd.registry.TileRegistry; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.Log; import org.cef.CefSettings;
import net.montoyo.wd.utilities.Multiblock;
import net.montoyo.wd.utilities.browser.WDBrowser;
import net.montoyo.wd.utilities.browser.handlers.DisplayHandler;
import net.montoyo.wd.utilities.browser.handlers.WDRouter;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import org.cef.browser.CefBrowser; import org.cef.browser.CefBrowser;
import org.cef.browser.CefMessageRouter; import org.cef.browser.CefFrame;
import org.cef.handler.CefDisplayHandler;
import org.cef.misc.CefCursorType; import org.cef.misc.CefCursorType;
import org.cef.network.CefRequest;
import org.joml.Vector3d;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@ -98,9 +97,10 @@ import java.lang.reflect.Field;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.util.*; import java.util.*;
import java.util.stream.Stream;
@Mod.EventBusSubscriber(modid = "webdisplays", value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) @Mod.EventBusSubscriber(modid = "webdisplays", value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public class ClientProxy extends SharedProxy implements ResourceManagerReloadListener { public class ClientProxy extends SharedProxy implements CefDisplayHandler/*, IJSQueryHandler*/, ResourceManagerReloadListener {
private static ClientProxy INSTANCE; private static ClientProxy INSTANCE;
@ -150,7 +150,7 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
BlockPos bpos = result.getBlockPos(); BlockPos bpos = result.getBlockPos();
if (result.getType() != HitResult.Type.BLOCK || mc.level.getBlockState(bpos).getBlock() != BlockRegistry.SCREEN_BLOCk.get()) { if (result.getType() != HitResult.Type.BLOCK || mc.level.getBlockState(bpos).getBlock() != BlockInit.blockScreen.get()) {
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.ONE_MINUS_DST_COLOR, GlStateManager.DestFactor.ONE_MINUS_SRC_COLOR, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.ONE_MINUS_DST_COLOR, GlStateManager.DestFactor.ONE_MINUS_SRC_COLOR, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
poseStack.blit(new ResourceLocation( poseStack.blit(new ResourceLocation(
@ -164,9 +164,9 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
BlockSide side = BlockSide.values()[result.getDirection().ordinal()]; BlockSide side = BlockSide.values()[result.getDirection().ordinal()];
Multiblock.findOrigin(mc.level, pos, side, null); Multiblock.findOrigin(mc.level, pos, side, null);
ScreenBlockEntity te = (ScreenBlockEntity) mc.level.getBlockEntity(pos.toBlock()); TileEntityScreen te = (TileEntityScreen) mc.level.getBlockEntity(pos.toBlock());
ScreenData sc = te.getScreen(side); TileEntityScreen.Screen sc = te.getScreen(side);
if (sc == null) return; if (sc == null) return;
@ -186,19 +186,11 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
ci.cancel(); ci.cancel();
} }
public List<ScreenBlockEntity> getScreens() {
return screenTracking;
}
public List<PadData> getPads() {
return padList;
}
public class PadData { public class PadData {
public CefBrowser view; public CefBrowser view;
public final UUID id;
private boolean isInHotbar; private boolean isInHotbar;
private final UUID id;
private long lastURLSent; private long lastURLSent;
public int activeCursor; public int activeCursor;
@ -206,11 +198,11 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
private PadData(String url, UUID id) { private PadData(String url, UUID id) {
String webUrl; String webUrl;
try { try {
webUrl = ScreenBlockEntity.url(url); webUrl = TileEntityScreen.url(url);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
view = WDBrowser.createBrowser(WebDisplays.applyBlacklist(webUrl), false); view = MCEF.createBrowser(WebDisplays.applyBlacklist(webUrl), false);
if (view instanceof MCEFBrowser browser) { if (view instanceof MCEFBrowser browser) {
browser.resize((int) WebDisplays.INSTANCE.padResX, (int) WebDisplays.INSTANCE.padResY); browser.resize((int) WebDisplays.INSTANCE.padResX, (int) WebDisplays.INSTANCE.padResY);
browser.setCursorChangeListener((cursor) -> { browser.setCursorChangeListener((cursor) -> {
@ -220,18 +212,11 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
isInHotbar = true; isInHotbar = true;
this.id = id; this.id = id;
} }
public void updateTime() {
lastURLSent = System.currentTimeMillis();
}
public long lastSent() {
return lastURLSent;
}
} }
private Minecraft mc; private Minecraft mc;
private MinePadRenderer minePadRenderer; private MinePadRenderer minePadRenderer;
// private JSQueryDispatcher jsDispatcher;
private LaserPointerRenderer laserPointerRenderer; private LaserPointerRenderer laserPointerRenderer;
private Screen nextScreen; private Screen nextScreen;
private boolean isF1Down; private boolean isF1Down;
@ -246,7 +231,7 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
private Map advancementToProgress; private Map advancementToProgress;
//Tracking //Tracking
private final ArrayList<ScreenBlockEntity> screenTracking = new ArrayList<>(); private final ArrayList<TileEntityScreen> screenTracking = new ArrayList<>();
private int lastTracked = 0; private int lastTracked = 0;
//MinePads Management //MinePads Management
@ -257,7 +242,7 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
/**************************************** INHERITED METHODS ****************************************/ /**************************************** INHERITED METHODS ****************************************/
@SubscribeEvent @SubscribeEvent
public static void onClientSetup(FMLClientSetupEvent event) { public static void onClientSetup(FMLClientSetupEvent event) {
BlockEntityRenderers.register(TileRegistry.SCREEN_BLOCK_ENTITY.get(), new ScreenRenderer.ScreenRendererProvider()); BlockEntityRenderers.register(TileInit.SCREEN_BLOCK_ENTITY.get(), new ScreenRenderer.ScreenRendererProvider());
} }
@SubscribeEvent @SubscribeEvent
@ -265,6 +250,10 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
event.register(ScreenModelLoader.SCREEN_LOADER.getPath(), new ScreenModelLoader()); event.register(ScreenModelLoader.SCREEN_LOADER.getPath(), new ScreenModelLoader());
} }
private static void registerBlockRenderLayers(RenderType layer, Block... blocks) {
Stream.of(blocks).forEach(block -> ItemBlockRenderTypes.setRenderLayer(block, layer));
}
@Override @Override
public void preInit() { public void preInit() {
super.preInit(); super.preInit();
@ -273,7 +262,12 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
} }
@Override @Override
public void onCefInit() { public void init() {
super.init();
}
@Override
public void onCefInit(/*CefInitEvent event*/) {
minePadRenderer = new MinePadRenderer(); minePadRenderer = new MinePadRenderer();
laserPointerRenderer = new LaserPointerRenderer(); laserPointerRenderer = new LaserPointerRenderer();
@ -287,8 +281,9 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
} }
); );
MCEF.getClient().addDisplayHandler(DisplayHandler.INSTANCE); // jsDispatcher = new JSQueryDispatcher(this);
MCEF.getClient().getHandle().addMessageRouter(CefMessageRouter.create(WDRouter.INSTANCE)); MCEF.getClient().addDisplayHandler(this);
// mcef.registerJSQueryHandler(this);
findAdvancementToProgressField(); findAdvancementToProgressField();
} }
@ -325,7 +320,7 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
} }
@Override @Override
public void trackScreen(ScreenBlockEntity tes, boolean track) { public void trackScreen(TileEntityScreen tes, boolean track) {
int idx = -1; int idx = -1;
for (int i = 0; i < screenTracking.size(); i++) { for (int i = 0; i < screenTracking.size(); i++) {
if (screenTracking.get(i) == tes) { if (screenTracking.get(i) == tes) {
@ -525,6 +520,55 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
GuiLoader.clearCache(); GuiLoader.clearCache();
} }
/**************************************** DISPLAY HANDLER METHODS ****************************************/
@Override
public void onAddressChange(CefBrowser browser, CefFrame cefFrame, String url) {
if (browser != null) {
long t = System.currentTimeMillis();
for (PadData pd : padList) {
if (pd.view == browser && t - pd.lastURLSent >= 1000) {
if (WebDisplays.isSiteBlacklisted(url))
pd.view.loadURL(WebDisplays.BLACKLIST_URL);
else {
pd.lastURLSent = t; //Avoid spamming the server with porn URLs
WDNetworkRegistry.INSTANCE.sendToServer(new C2SMessageMinepadUrl(pd.id, url));
}
break;
}
}
for (TileEntityScreen tes : screenTracking)
tes.updateClientSideURL(browser, url);
}
}
@Override
public void onTitleChange(CefBrowser cefBrowser, String s) {
}
@Override
public boolean onTooltip(CefBrowser cefBrowser, String s) {
return false;
}
@Override
public void onStatusMessage(CefBrowser cefBrowser, String s) {
}
@Override
public boolean onConsoleMessage(CefBrowser cefBrowser, CefSettings.LogSeverity logSeverity, String s, String s1, int i) {
return false;
}
@Override
public boolean onCursorChange(CefBrowser cefBrowser, int i) {
return false;
}
/**************************************** JS HANDLER METHODS ****************************************/ /**************************************** JS HANDLER METHODS ****************************************/
// @Override // @Override
@ -567,18 +611,47 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
/**************************************** EVENT METHODS ****************************************/ /**************************************** EVENT METHODS ****************************************/
// @SubscribeEvent
// public void onBakeModel(ModelBakeEvent ev) {
// for(ResourceModelPair pair : modelBakers)
// ev.getModelRegistry().put(pair.getResourceLocation(), pair.getModel());
// }
/* @SubscribeEvent
public void onRegisterModels(ModelRegistryEvent ev) {
final WebDisplays wd = WebDisplays.INSTANCE;
//I hope I'm doing this right because it doesn't seem like it...
registerItemModel(wd.blockScreen.getItem(), 0, "inventory");
ModelLoaderRegistry.setCustomModelResourceLocation(wd.blockPeripheral.getItem(), 0, new ModelResourceLocation("webdisplays:kb_inv", "normal"));
registerItemModel(wd.blockPeripheral.getItem(), 1, "facing=2,type=ccinterface");
registerItemModel(wd.blockPeripheral.getItem(), 2, "facing=2,type=cointerface");
registerItemModel(wd.blockPeripheral.getItem(), 3, "facing=0,type=remotectrl");
registerItemModel(wd.blockPeripheral.getItem(), 7, "facing=0,type=redstonectrl");
registerItemModel(wd.blockPeripheral.getItem(), 11, "facing=0,type=server");
registerItemModel(wd.itemScreenCfg, 0, "normal");
registerItemModel(wd.itemOwnerThief, 0, "normal");
registerItemModel(wd.itemLinker, 0, "normal");
registerItemModel(wd.itemMinePad, 0, "normal");
registerItemModel(wd.itemMinePad, 1, "normal");
registerItemModel(wd.itemLaserPointer, 0, "normal");
registerItemMultiModels(wd.itemUpgrade);
registerItemMultiModels(wd.itemCraftComp);
registerItemMultiModels(wd.itemAdvIcon);
} */
@SubscribeEvent @SubscribeEvent
public void onLevelTick(TickEvent.LevelTickEvent ev) { public void onLevelTick(TickEvent.LevelTickEvent ev) {
if (!ev.side.equals(LogicalSide.CLIENT)) return; if (!ev.side.equals(LogicalSide.CLIENT)) return;
if (ev.phase != TickEvent.Phase.END) return; if (ev.phase != TickEvent.Phase.END) return;
//Unload/load screens depending on client player distance //Unload/load screens depending on client player distance
if (mc.player == null || screenTracking.isEmpty()) if (mc.player != null || !screenTracking.isEmpty())
return; return;
int id = lastTracked % screenTracking.size(); int id = lastTracked % screenTracking.size();
ScreenBlockEntity tes = screenTracking.get(id); TileEntityScreen tes = screenTracking.get(id);
if (!tes.getLevel().equals(ev.level)) if (!tes.getLevel().equals(ev.level))
return; return;
@ -590,31 +663,27 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
if (!tes.isLoaded()) if (!tes.isLoaded())
tes.load(); tes.load();
} else { } else {
EntityRenderDispatcher entityRenderDispatcher = mc.getEntityRenderDispatcher(); double dist = Double.POSITIVE_INFINITY;
if (entityRenderDispatcher == null) return; for (int i = 0; i < tes.screenCount(); i++) {
Camera camera = entityRenderDispatcher.camera; TileEntityScreen.Screen scrn = tes.getScreen(i);
Entity entity = null;
// ide inspection says this is a bunch of constant expressions Vector3d pos = new Vector3d(
// THIS IS NOT THE CASE scrn.side.right.x * scrn.size.x + scrn.size.y * scrn.side.up.x,
// a crash HAS occurred because of this going unchecked, and I'm confused about it scrn.side.right.y * scrn.size.x + scrn.size.y * scrn.side.up.y,
scrn.side.right.z * scrn.size.x + scrn.size.y * scrn.side.up.z
);
//noinspection ConstantValue double dist2 = mc.player.distanceToSqr(pos.x, pos.y, pos.z);
if (camera != null) entity = camera.getEntity(); dist = Math.min(dist, dist2);
//noinspection ConstantValue
if (entity == null) entity = mc.player;
//noinspection ConstantValue
if (entity != null) {
double dist = distanceTo(tes, entity.getPosition(0));
if (tes.isLoaded()) {
if (dist > WebDisplays.INSTANCE.unloadDistance2 * 16)
tes.deactivate();
// else if (ClientConfig.AutoVolumeControl.enableAutoVolume)
// tes.updateTrackDistance(dist, 80); //ToDo find master volume
} else if (dist <= WebDisplays.INSTANCE.loadDistance2 * 16)
tes.activate();
} }
if (tes.isLoaded()) {
if (dist > WebDisplays.INSTANCE.unloadDistance2)
tes.unload();
// else if (ClientConfig.AutoVolumeControl.enableAutoVolume)
// tes.updateTrackDistance(dist, 80); //ToDo find master volume
} else if (dist <= WebDisplays.INSTANCE.loadDistance2)
tes.load();
} }
} }
@ -696,6 +765,9 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
ItemLaserPointer.deselect(mc); ItemLaserPointer.deselect(mc);
} }
// //Handle JS queries
// jsDispatcher.handleQueries();
//Miniserv //Miniserv
if (msClientStarted && mc.player == null) { if (msClientStarted && mc.player == null) {
msClientStarted = false; msClientStarted = false;
@ -708,10 +780,10 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
Item item = ev.getItemStack().getItem(); Item item = ev.getItemStack().getItem();
IItemRenderer renderer; IItemRenderer renderer;
if (ItemRegistry.MINEPAD.isPresent() && ItemRegistry.LASER_POINTER.isPresent()) { if (ItemInit.MINEPAD.isPresent() && ItemInit.LASER_POINTER.isPresent()) {
if (item == ItemRegistry.MINEPAD.get()) if (item == ItemInit.MINEPAD.get())
renderer = minePadRenderer; renderer = minePadRenderer;
else if (item == ItemRegistry.LASER_POINTER.get()) else if (item == ItemInit.LASER_POINTER.get())
renderer = laserPointerRenderer; renderer = laserPointerRenderer;
else else
return; return;
@ -751,8 +823,8 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
for (int i = 0; i < cnt; i++) { for (int i = 0; i < cnt; i++) {
ItemStack item = inv.get(i); ItemStack item = inv.get(i);
if (ItemRegistry.MINEPAD.isPresent()) { if (ItemInit.MINEPAD.isPresent()) {
if (item.getItem() == ItemRegistry.MINEPAD.get()) { if (item.getItem() == ItemInit.MINEPAD.get()) {
CompoundTag tag = item.getTag(); CompoundTag tag = item.getTag();
if (tag != null && tag.contains("PadID")) if (tag != null && tag.contains("PadID"))
@ -784,15 +856,15 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
public static final class ScreenSidePair { public static final class ScreenSidePair {
public ScreenBlockEntity tes; public TileEntityScreen tes;
public BlockSide side; public BlockSide side;
} }
public boolean findScreenFromBrowser(CefBrowser browser, ScreenSidePair pair) { public boolean findScreenFromBrowser(CefBrowser browser, ScreenSidePair pair) {
for (ScreenBlockEntity tes : screenTracking) { for (TileEntityScreen tes : screenTracking) {
for (int i = 0; i < tes.screenCount(); i++) { for (int i = 0; i < tes.screenCount(); i++) {
ScreenData scr = tes.getScreen(i); TileEntityScreen.Screen scr = tes.getScreen(i);
if (scr.browser == browser) { if (scr.browser == browser) {
pair.tes = tes; pair.tes = tes;
@ -833,7 +905,7 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
public static void onDrawSelection(RenderHighlightEvent event) { public static void onDrawSelection(RenderHighlightEvent event) {
if (event.getTarget() instanceof BlockHitResult bhr) { if (event.getTarget() instanceof BlockHitResult bhr) {
BlockState state = Minecraft.getInstance().level.getBlockState(bhr.getBlockPos()); BlockState state = Minecraft.getInstance().level.getBlockState(bhr.getBlockPos());
if (state.getBlock() instanceof ScreenBlock screen) { if (state.getBlock() instanceof BlockScreen screen) {
Vector3i vec = new Vector3i(bhr.getBlockPos().getX(), bhr.getBlockPos().getY(), bhr.getBlockPos().getZ()); Vector3i vec = new Vector3i(bhr.getBlockPos().getX(), bhr.getBlockPos().getY(), bhr.getBlockPos().getZ());
BlockSide side = BlockSide.fromInt(bhr.getDirection().ordinal()); BlockSide side = BlockSide.fromInt(bhr.getDirection().ordinal());
Multiblock.findOrigin( Multiblock.findOrigin(
@ -845,7 +917,7 @@ public class ClientProxy extends SharedProxy implements ResourceManagerReloadLis
BlockEntity be = Minecraft.getInstance().level.getBlockEntity( BlockEntity be = Minecraft.getInstance().level.getBlockEntity(
pos pos
); );
if (be instanceof ScreenBlockEntity tes) { if (be instanceof TileEntityScreen tes) {
if (tes.getScreen(side) != null) { if (tes.getScreen(side) != null) {
event.setCanceled(true); event.setCanceled(true);
} }

View File

@ -8,7 +8,7 @@ import net.montoyo.wd.miniserv.Constants;
import net.montoyo.wd.miniserv.client.Client; import net.montoyo.wd.miniserv.client.Client;
import net.montoyo.wd.miniserv.client.ClientTaskGetFile; import net.montoyo.wd.miniserv.client.ClientTaskGetFile;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import org.cef.callback.CefCallback; import org.cef.callback.CefCallback;
import org.cef.handler.CefResourceHandler; import org.cef.handler.CefResourceHandler;
import org.cef.misc.IntRef; import org.cef.misc.IntRef;
@ -16,8 +16,8 @@ import org.cef.misc.StringRef;
import org.cef.network.CefRequest; import org.cef.network.CefRequest;
import org.cef.network.CefResponse; import org.cef.network.CefResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID; import java.util.UUID;
public class WDScheme implements CefResourceHandler { public class WDScheme implements CefResourceHandler {
@ -27,7 +27,6 @@ public class WDScheme implements CefResourceHandler {
private boolean isErrorPage; private boolean isErrorPage;
String url; String url;
boolean onlyError = false;
public WDScheme(String url) { public WDScheme(String url) {
this.url = url; this.url = url;
@ -37,94 +36,79 @@ public class WDScheme implements CefResourceHandler {
public boolean processRequest(CefRequest cefRequest, CefCallback cefCallback) { public boolean processRequest(CefRequest cefRequest, CefCallback cefCallback) {
url = cefRequest.getURL(); url = cefRequest.getURL();
url = url.substring("webdisplays://".length());
int pos = url.indexOf('/'); int pos = url.indexOf('/');
if (pos < 0) if(pos < 0)
return false; return false;
String uuidStr = url.substring(0, pos); String uuidStr = url.substring(0, pos);
String fileStr = url.substring(pos + 1); String fileStr = url.substring(pos + 1);
fileStr = URLDecoder.decode(fileStr, StandardCharsets.UTF_8); try {
fileStr = URLDecoder.decode(fileStr, "UTF-8");
if (uuidStr.isEmpty() || Util.isFileNameInvalid(fileStr)) { } catch(UnsupportedEncodingException ex) {
// invalid URL or no UUID Log.warningEx("UTF-8 isn't supported... yeah... and I'm a billionaire...", ex);
onlyError = true;
cefCallback.Continue();
return true;
} }
if(uuidStr.isEmpty() || Util.isFileNameInvalid(fileStr))
return false;
UUID uuid; UUID uuid;
try { try {
uuid = UUID.fromString(uuidStr); uuid = UUID.fromString(uuidStr);
} catch (IllegalArgumentException ex) { } catch(IllegalArgumentException ex) {
// invalid UUID return false; //Invalid UUID
onlyError = true;
cefCallback.Continue();
return true;
} }
task = new ClientTaskGetFile(uuid, fileStr); task = new ClientTaskGetFile(uuid, fileStr);
boolean doContinue = Client.getInstance().addTask(task); return Client.getInstance().addTask(task) ? true : false;
if (doContinue) cefCallback.Continue();
return doContinue;
} }
@Override @Override
public void getResponseHeaders(CefResponse cefResponse, IntRef contentLength, StringRef redir) { public void getResponseHeaders(CefResponse cefResponse, IntRef intRef, StringRef stringRef) {
int status; Log.info("Waiting for response...");
if (onlyError) { int status = task.waitForResponse();
status = Constants.GETF_STATUS_BAD_NAME; Log.info("Got response %d", status);
} else {
Log.info("Waiting for response...");
status = task.waitForResponse();
Log.info("Got response %d", status);
if (status == 0) { if(status == 0) {
//OK //OK
int extPos = task.getFileName().lastIndexOf('.'); int extPos = task.getFileName().lastIndexOf('.');
if (extPos >= 0) { if(extPos >= 0) {
String mime = mapMime(task.getFileName().substring(extPos + 1)); String mime = mapMime(task.getFileName().substring(extPos + 1));
if (mime != null) if(mime != null)
cefResponse.setMimeType(mime); cefResponse.setMimeType(mime);
}
cefResponse.setStatus(200);
cefResponse.setStatusText("OK");
contentLength.set(0);
return;
} }
cefResponse.setStatus(200);
cefResponse.setStatusText("OK");
cefResponse.setHeaderByName("content-length", "" + -1, true);
return;
} }
int errCode; int errCode;
String errStr; String errStr;
if (status == Constants.GETF_STATUS_NOT_FOUND) { if(status == Constants.GETF_STATUS_NOT_FOUND) {
errCode = 404; errCode = 404;
errStr = "Not Found"; errStr = "Not Found";
} else if (status == Constants.GETF_STATUS_TIMED_OUT) {
errCode = 408;
errStr = "Timed Out";
} else if (status == Constants.GETF_STATUS_BAD_NAME) {
errCode = 418;
errStr = "I'm a teapot";
} else { } else {
errCode = 500; errCode = 500;
errStr = "Internal Server Error"; errStr = "Internal Server Error";
} }
// reporting the actual status and text makes CEF not display the page cefResponse.setStatus(errCode);
cefResponse.setStatus(200); cefResponse.setStatusText(errStr);
cefResponse.setStatusText("OK");
cefResponse.setMimeType("text/html");
dataToWrite = String.format(ERROR_PAGE, errCode, errStr).getBytes(StandardCharsets.UTF_8); try {
dataOffset = 0; dataToWrite = String.format(ERROR_PAGE, errCode, errStr).getBytes("UTF-8");
amountToWrite = dataToWrite.length; dataOffset = 0;
isErrorPage = true; amountToWrite = dataToWrite.length;
contentLength.set(0); isErrorPage = true;
cefResponse.setHeaderByName("content-length", "" + amountToWrite, true);
} catch(UnsupportedEncodingException ex) {
cefResponse.setHeaderByName("content-length", "" + 0, true);
// cefResponse.setResponseLength(0);
}
} }
private byte[] dataToWrite; private byte[] dataToWrite;
@ -132,10 +116,10 @@ public class WDScheme implements CefResourceHandler {
private int amountToWrite; private int amountToWrite;
@Override @Override
public boolean readResponse(byte[] output, int bytesToRead, IntRef bytesRead, CefCallback cefCallback) { public boolean readResponse(byte[] bytes, int i, IntRef intRef, CefCallback cefCallback) {
if (dataToWrite == null) { if(dataToWrite == null) {
if (isErrorPage) { if(isErrorPage) {
bytesRead.set(0); // data.setAmountRead(0);
return false; return false;
} }
@ -143,25 +127,25 @@ public class WDScheme implements CefResourceHandler {
dataOffset = 3; //packet ID + size dataOffset = 3; //packet ID + size
amountToWrite = task.getDataLength(); amountToWrite = task.getDataLength();
if (amountToWrite <= 0) { if(amountToWrite <= 0) {
dataToWrite = null; dataToWrite = null;
bytesRead.set(0); // data.setAmountRead(0);
return false; return false;
} }
} }
int toWrite = bytesToRead; // int toWrite = data.getBytesToRead();
if (toWrite > amountToWrite) // if(toWrite > amountToWrite)
toWrite = amountToWrite; // toWrite = amountToWrite;
System.arraycopy(dataToWrite, dataOffset, output, 0, toWrite); // System.arraycopy(dataToWrite, dataOffset, data.getDataArray(), 0, toWrite);
bytesRead.set(toWrite); // data.setAmountRead(toWrite);
dataOffset += toWrite; // dataOffset += toWrite;
amountToWrite -= toWrite; // amountToWrite -= toWrite;
if (amountToWrite <= 0) { if(amountToWrite <= 0) {
if (!isErrorPage) if(!isErrorPage)
task.nextData(); task.nextData();
dataToWrite = null; dataToWrite = null;
@ -172,9 +156,6 @@ public class WDScheme implements CefResourceHandler {
@Override @Override
public void cancel() { public void cancel() {
Log.info("Scheme query canceled or finished.");
if (!onlyError)
task.cancel();
} }
public static String mapMime(String ext) { public static String mapMime(String ext) {

View File

@ -1,116 +0,0 @@
package net.montoyo.wd.client.audio;
import net.minecraft.client.resources.sounds.Sound;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.client.sounds.AudioStream;
import net.minecraft.client.sounds.SoundBufferLibrary;
import net.minecraft.client.sounds.SoundManager;
import net.minecraft.client.sounds.WeighedSoundEvents;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.util.valueproviders.SampledFloat;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.entity.ScreenData;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture;
public class WDAudioSource implements SoundInstance {
private static final ResourceLocation location = new ResourceLocation("webdisplays:audio_source");
private static final WeighedSoundEvents events = new WeighedSoundEvents(
location, "webdisplays.browser"
);
private static final SampledFloat CONST_1 = new SampledFloat() {
@Override
public float sample(RandomSource pRandom) {
return 1.0f;
}
};
private final Sound sound = new Sound(
"unused",
CONST_1,
CONST_1,
1, Sound.Type.SOUND_EVENT,
true, false,
100
);
ScreenBlockEntity blockEntity;
ScreenData data;
public WDAudioSource(ScreenBlockEntity blockEntity, ScreenData data) {
this.blockEntity = blockEntity;
this.data = data;
}
@Override
public ResourceLocation getLocation() {
return location;
}
@Nullable
@Override
public WeighedSoundEvents resolve(SoundManager pManager) {
return events;
}
@Override
public CompletableFuture<AudioStream> getStream(SoundBufferLibrary soundBuffers, Sound sound, boolean looping) {
return null;
}
@Override
public Sound getSound() {
return sound;
}
@Override
public SoundSource getSource() {
return SoundSource.RECORDS;
}
@Override
public boolean isLooping() {
return true;
}
@Override
public boolean isRelative() {
return false;
}
@Override
public int getDelay() {
return 0;
}
@Override
public float getVolume() {
return blockEntity.ytVolume;
}
@Override
public float getPitch() {
return 1;
}
@Override
public double getX() {
return blockEntity.getBlockPos().getX();
}
@Override
public double getY() {
return blockEntity.getBlockPos().getY();
}
@Override
public double getZ() {
return blockEntity.getBlockPos().getZ();
}
@Override
public Attenuation getAttenuation() {
return Attenuation.LINEAR;
}
}

View File

@ -4,59 +4,44 @@
package net.montoyo.wd.client.gui; package net.montoyo.wd.client.gui;
import com.cinemamod.mcef.MCEFBrowser;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Axis;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.loading.FMLPaths; import net.minecraftforge.fml.loading.FMLPaths;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.gui.camera.KeyboardCamera;
import net.montoyo.wd.client.gui.controls.Button; import net.montoyo.wd.client.gui.controls.Button;
import net.montoyo.wd.client.gui.controls.Control; import net.montoyo.wd.client.gui.controls.Control;
import net.montoyo.wd.client.gui.controls.Label; import net.montoyo.wd.client.gui.controls.Label;
import net.montoyo.wd.client.gui.loading.FillControl; import net.montoyo.wd.client.gui.loading.FillControl;
import net.montoyo.wd.controls.builtin.ClickControl; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.TypeData;
import net.montoyo.wd.utilities.math.Vector2i; import net.montoyo.wd.utilities.Util;
import net.montoyo.wd.utilities.serialization.TypeData;
import net.montoyo.wd.utilities.serialization.Util;
import org.cef.browser.CefBrowser;
import org.cef.misc.CefCursorType;
import org.joml.Matrix4f;
import org.joml.Vector4f;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import org.vivecraft.client_vr.gameplay.VRPlayer; import org.vivecraft.client_vr.gameplay.VRPlayer;
import org.vivecraft.client_vr.gameplay.screenhandlers.KeyboardHandler; import org.vivecraft.client_vr.gameplay.screenhandlers.KeyboardHandler;
//import org.vivecraft.gameplay.VRPlayer;
//import org.vivecraft.gameplay.screenhandlers.KeyboardHandler;
import java.io.*; import java.io.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public class GuiKeyboard extends WDScreen { public class GuiKeyboard extends WDScreen {
private static final String WARNING_FNAME = "wd_keyboard_warning.txt"; private static final String WARNING_FNAME = "wd_keyboard_warning.txt";
private ScreenBlockEntity tes; private TileEntityScreen tes;
private BlockSide side; private BlockSide side;
private ScreenData data;
private final ArrayList<TypeData> evStack = new ArrayList<>(); private final ArrayList<TypeData> evStack = new ArrayList<>();
private BlockPos kbPos; private BlockPos kbPos;
private boolean showWarning = true; private boolean showWarning = true;
@ -71,7 +56,7 @@ public class GuiKeyboard extends WDScreen {
super(Component.nullToEmpty(null)); super(Component.nullToEmpty(null));
} }
public GuiKeyboard(ScreenBlockEntity tes, BlockSide side, BlockPos kbPos) { public GuiKeyboard(TileEntityScreen tes, BlockSide side, BlockPos kbPos) {
this(); this();
this.tes = tes; this.tes = tes;
this.side = side; this.side = side;
@ -156,45 +141,20 @@ public class GuiKeyboard extends WDScreen {
if (vivecraftPresent) if (vivecraftPresent)
if (VRPlayer.get() != null) if (VRPlayer.get() != null)
KeyboardHandler.setOverlayShowing(true); KeyboardHandler.setOverlayShowing(true);
KeyboardCamera.focus(tes, side);
data = tes.getScreen(side);
CefBrowser browser = data.browser;
((MCEFBrowser) browser).setCursor(CefCursorType.fromId(data.mouseType));
((MCEFBrowser) browser).setCursorChangeListener((id) -> {
data.mouseType = id;
((MCEFBrowser) browser).setCursor(CefCursorType.fromId(id));
});
}
@Override
public void removed() {
super.removed();
if (vivecraftPresent)
if (VRPlayer.get() != null)
KeyboardHandler.setOverlayShowing(false);
KeyboardCamera.focus(null, null);
CefBrowser browser = data.browser;
if (browser instanceof MCEFBrowser mcef) {
mcef.setCursor(CefCursorType.POINTER);
mcef.setCursorChangeListener((cursor) -> data.mouseType = cursor);
}
} }
@Override @Override
public void onClose() { public void onClose() {
removed(); if (vivecraftPresent)
if (VRPlayer.get() != null)
KeyboardHandler.setOverlayShowing(false);
super.onClose(); super.onClose();
this.minecraft.popGuiLayer();
} }
@Override @Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) { public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (quitOnEscape && keyCode == GLFW.GLFW_KEY_ESCAPE) { if(quitOnEscape && keyCode == GLFW.GLFW_KEY_ESCAPE)
onClose(); Minecraft.getInstance().setScreen(null);
return true;
}
addKey(new TypeData(TypeData.Action.PRESS, keyCode, modifiers, scanCode)); addKey(new TypeData(TypeData.Action.PRESS, keyCode, modifiers, scanCode));
return super.keyPressed(keyCode, scanCode, modifiers); return super.keyPressed(keyCode, scanCode, modifiers);
} }
@ -283,89 +243,4 @@ public class GuiKeyboard extends WDScreen {
return bp.equals(kbPos) || (bp.equals(tes.getBlockPos()) && side == this.side); return bp.equals(kbPos) || (bp.equals(tes.getBlockPos()) && side == this.side);
} }
protected void mouse(double mouseX, double mouseY, Consumer<Vector2i> func) {
float pct = Minecraft.getInstance().getPartialTick();
double fov = Minecraft.getInstance().gameRenderer.getFov(
Minecraft.getInstance().getEntityRenderDispatcher().camera,
pct, true
);
mouseX /= width;
mouseY /= height;
mouseX -= 0.5;
mouseY -= 0.5;
mouseY = -mouseY;
Matrix4f proj = Minecraft.getInstance().gameRenderer.getProjectionMatrix(fov);
Entity e = Minecraft.getInstance().getEntityRenderDispatcher().camera.getEntity();
PoseStack camera = new PoseStack();
float[] angle = KeyboardCamera.getAngle(e, pct);
camera.mulPose(Axis.XP.rotationDegrees(angle[0]));
camera.mulPose(Axis.YP.rotationDegrees(angle[1] + 180.0F));
Vector4f coord = new Vector4f(2f * (float) mouseX, 2 * (float) mouseY, 0, 1f);
coord.add(proj.invert().transform(coord));
coord = camera.last().pose().invert().transform(coord);
Vec3 vec3 = e.getEyePosition(pct);
Vec3 vec31 = new Vec3(coord.x, coord.y, coord.z).normalize();
BlockHitResult result = tes.trace(side, vec3, vec31);
if (result.getType() != HitResult.Type.MISS) {
tes.interact(result, func);
}
}
@Override
public void mouseMoved(double mouseX, double mouseY) {
mouse(mouseX, mouseY, (hit) -> {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserMove(tes, side, hit));
});
super.mouseMoved(mouseX, mouseY);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
mouse(mouseX, mouseY, (hit) -> {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
tes.handleMouseEvent(side, ClickControl.ControlType.DOWN, hit, button);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserDown(tes, side, hit, button));
});
KeyboardCamera.setMouse(button, true);
return super.mouseClicked(mouseX, mouseY, button);
}
@Override
public boolean mouseReleased(double mouseX, double mouseY, int button) {
mouse(mouseX, mouseY, (hit) -> {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
tes.handleMouseEvent(side, ClickControl.ControlType.UP, hit, button);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserUp(tes, side, button));
});
KeyboardCamera.setMouse(button, false);
return super.mouseReleased(mouseX, mouseY, button);
}
@Override
public void tick() {
double mouseX = Minecraft.getInstance().mouseHandler.xpos() / Minecraft.getInstance().getWindow().getWidth();
double mouseY = Minecraft.getInstance().mouseHandler.ypos() / Minecraft.getInstance().getWindow().getHeight();
mouse(mouseX * width, mouseY * height, (hit) -> {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserMove(tes, side, hit));
});
super.tick();
}
} }

View File

@ -4,26 +4,20 @@
package net.montoyo.wd.client.gui; package net.montoyo.wd.client.gui;
import com.cinemamod.mcef.MCEF;
import com.cinemamod.mcef.MCEFBrowser; import com.cinemamod.mcef.MCEFBrowser;
import com.google.gson.JsonObject;
import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.platform.InputConstants;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.*;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.Tesselator;
import com.mojang.blaze3d.vertex.VertexFormat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.locale.Language;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.ClientProxy; import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.utilities.browser.WDBrowser; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.browser.handlers.js.Scripts; import org.cef.browser.CefBrowserOsr;
import net.montoyo.wd.utilities.data.BlockSide;
import org.cef.misc.CefCursorType; import org.cef.misc.CefCursorType;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
@ -122,12 +116,6 @@ public class GuiMinePad extends WDScreen {
} }
RenderSystem.enableCull(); RenderSystem.enableCull();
graphics.drawString(
minecraft.font, Language.getInstance().getOrDefault(
"webdisplays.gui.minepad.close"
), (int) vx + 4, (int) vy - minecraft.font.lineHeight - 3, 16777215, true
);
} }
@Override @Override
@ -153,8 +141,8 @@ public class GuiMinePad extends WDScreen {
/* copied from MCEF */ /* copied from MCEF */
public boolean keyChanged(int keyCode, int scanCode, int modifiers, boolean pressed) { public boolean keyChanged(int keyCode, int scanCode, int modifiers, boolean pressed) {
assert minecraft != null; assert minecraft != null;
if ((modifiers & GLFW.GLFW_MOD_SHIFT) == GLFW.GLFW_MOD_SHIFT && keyCode == GLFW.GLFW_KEY_ESCAPE) { if (keyCode == GLFW.GLFW_KEY_ESCAPE) {
onClose(); minecraft.setScreen(null);
return true; return true;
} }
@ -215,55 +203,21 @@ public class GuiMinePad extends WDScreen {
return super.mouseScrolled(mouseX, mouseY, amount); return super.mouseScrolled(mouseX, mouseY, amount);
} }
public void capturedMouse(double scaledX, double scaledY, int sx, int sy) {
double centerX = (int) (0.5 * (double) this.minecraft.getWindow().getGuiScaledWidth());
double centerY = (int) (0.5 * (double) this.minecraft.getWindow().getGuiScaledHeight());
if (sx == (int) centerX && sy == (int) centerY) return;
double mx = (centerX - vx) / vw;
double my = (centerY - vy) / vh;
double scaledCentX = (mx * WebDisplays.INSTANCE.padResX);
double scaledCentY = (my * WebDisplays.INSTANCE.padResY);
double deltX = scaledX - scaledCentX;
double deltY = scaledY - scaledCentY;
String scr = Scripts.MOUSE_EVENT;
pad.view.executeJavaScript(
scr
.replace("%xCoord%", "" + (int) centerX)
.replace("%yCoord%", "" + (int) centerY)
.replace("%xDelta%", "" + (deltX))
.replace("%yDelta%", "" + (deltY)),
"WebDisplays", 0
);
// lock mouse
try {
double xpos = (this.minecraft.getWindow().getScreenWidth() / 2);
double ypos = (this.minecraft.getWindow().getScreenHeight() / 2);
GLFW.glfwSetCursorPos(minecraft.getWindow().getWindow(), xpos, ypos);
} catch (Throwable ignored) {
}
}
public void mouse(int btn, boolean pressed, int sx, int sy, double scrollAmount) { public void mouse(int btn, boolean pressed, int sx, int sy, double scrollAmount) {
double mx = (sx - vx) / vw; double mx = (sx - vx) / vw;
double my = (sy - vy) / vh; double my = (sy - vy) / vh;
if (pad.view != null && mx >= 0 && mx <= 1) { if (pad.view != null && mx >= 0 && mx <= 1) {
//Scale again according to the webview //Scale again according to the webview
int scaledX = (int) (mx * WebDisplays.INSTANCE.padResX); sx = (int) (mx * WebDisplays.INSTANCE.padResX);
int scaledY = (int) (my * WebDisplays.INSTANCE.padResY); sy = (int) (my * WebDisplays.INSTANCE.padResY);
if (btn == -1) { if (btn == -1)
if (locked) ((MCEFBrowser) pad.view).sendMouseMove(sx, sy);
capturedMouse(mx * WebDisplays.INSTANCE.padResX, my * WebDisplays.INSTANCE.padResY, sx, sy); else if (pressed)
else ((MCEFBrowser) pad.view).sendMouseMove(scaledX, scaledY); ((MCEFBrowser) pad.view).sendMousePress(sx, sy, btn);
} else if (pressed) else
((MCEFBrowser) pad.view).sendMousePress(scaledX, scaledY, btn); ((MCEFBrowser) pad.view).sendMouseRelease(sx, sy, btn);
else ((MCEFBrowser) pad.view).sendMouseRelease(scaledX, scaledY, btn);
pad.view.setFocus(true); pad.view.setFocus(true);
} }
} }
@ -287,7 +241,6 @@ public class GuiMinePad extends WDScreen {
public void tick() { public void tick() {
if (pad.view == null) if (pad.view == null)
minecraft.setScreen(null); //In case the user dies with the pad in the hand minecraft.setScreen(null); //In case the user dies with the pad in the hand
pollElement();
} }
@Override @Override
@ -298,10 +251,6 @@ public class GuiMinePad extends WDScreen {
@Override @Override
public void removed() { public void removed() {
super.removed(); super.removed();
InputConstants.updateRawMouseInput(
minecraft.getWindow().getWindow(),
Minecraft.getInstance().options.rawMouseInput().get()
);
if (pad.view instanceof MCEFBrowser browser) { if (pad.view instanceof MCEFBrowser browser) {
browser.setCursor(CefCursorType.POINTER); browser.setCursor(CefCursorType.POINTER);
browser.setCursorChangeListener((cursor) -> { browser.setCursorChangeListener((cursor) -> {
@ -314,44 +263,5 @@ public class GuiMinePad extends WDScreen {
public void onClose() { public void onClose() {
super.onClose(); super.onClose();
removed(); removed();
this.minecraft.popGuiLayer();
}
boolean locked = false;
double lockCenterX = -1;
double lockCenterY = -1;
protected void updateCrd(JsonObject obj) {
if (obj.getAsJsonPrimitive("exists").getAsBoolean()) {
locked = true;
RenderSystem.recordRenderCall(() -> {
InputConstants.updateRawMouseInput(
minecraft.getWindow().getWindow(),
obj.getAsJsonPrimitive("unadjust").getAsBoolean()
);
GLFW.glfwSetInputMode(Minecraft.getInstance().getWindow().getWindow(), 208897, GLFW.GLFW_CURSOR_DISABLED);
});
lockCenterX = obj.getAsJsonPrimitive("x").getAsDouble() + obj.getAsJsonPrimitive("w").getAsDouble() / 2;
lockCenterY = obj.getAsJsonPrimitive("y").getAsDouble() + obj.getAsJsonPrimitive("h").getAsDouble() / 2;
} else {
if (locked) {
locked = false;
RenderSystem.recordRenderCall(()->{
InputConstants.updateRawMouseInput(
minecraft.getWindow().getWindow(),
Minecraft.getInstance().options.rawMouseInput().get()
);
GLFW.glfwSetInputMode(Minecraft.getInstance().getWindow().getWindow(), 208897, GLFW.GLFW_CURSOR_NORMAL);
GLFW.glfwSetCursor(Minecraft.getInstance().getWindow().getWindow(), CefCursorType.fromId(pad.activeCursor).glfwId);
});
}
}
}
protected void pollElement() {
if (pad.view instanceof WDBrowser browser) {
JsonObject object = browser.pointerLockElement().getObj();
if (object != null) updateCrd(object);
}
} }
} }

View File

@ -7,11 +7,16 @@ package net.montoyo.wd.client.gui;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.client.gui.controls.Button; import net.montoyo.wd.client.gui.controls.Button;
import net.montoyo.wd.client.gui.controls.TextField; import net.montoyo.wd.client.gui.controls.TextField;
import net.montoyo.wd.client.gui.loading.FillControl; import net.montoyo.wd.client.gui.loading.FillControl;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.net.server_bound.C2SMessageRedstoneCtrl;
import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Util;
import net.montoyo.wd.utilities.Vector3i;
import javax.annotation.Nullable; import javax.annotation.Nullable;

View File

@ -15,16 +15,11 @@ import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.gui.controls.*; import net.montoyo.wd.client.gui.controls.*;
import net.montoyo.wd.client.gui.loading.FillControl; import net.montoyo.wd.client.gui.loading.FillControl;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.item.WDItem; import net.montoyo.wd.item.WDItem;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -35,7 +30,7 @@ import java.util.UUID;
public class GuiScreenConfig extends WDScreen { public class GuiScreenConfig extends WDScreen {
//Screen data //Screen data
private final ScreenBlockEntity tes; private final TileEntityScreen tes;
private final BlockSide side; private final BlockSide side;
private NameUUIDPair owner; private NameUUIDPair owner;
private NameUUIDPair[] friends; private NameUUIDPair[] friends;
@ -124,7 +119,7 @@ public class GuiScreenConfig extends WDScreen {
private CheckBox[] friendBoxes; private CheckBox[] friendBoxes;
private CheckBox[] otherBoxes; private CheckBox[] otherBoxes;
public GuiScreenConfig(Component component, ScreenBlockEntity tes, BlockSide side, NameUUIDPair[] friends, int fr, int or) { public GuiScreenConfig(Component component, TileEntityScreen tes, BlockSide side, NameUUIDPair[] friends, int fr, int or) {
super(component); super(component);
this.tes = tes; this.tes = tes;
this.side = side; this.side = side;
@ -152,7 +147,7 @@ public class GuiScreenConfig extends WDScreen {
boxOClick.setUserdata(ScreenRights.INTERACT); boxOClick.setUserdata(ScreenRights.INTERACT);
boxOSetUrl.setUserdata(ScreenRights.CHANGE_URL); boxOSetUrl.setUserdata(ScreenRights.CHANGE_URL);
ScreenData scr = tes.getScreen(side); TileEntityScreen.Screen scr = tes.getScreen(side);
if(scr != null) { if(scr != null) {
owner = scr.owner; owner = scr.owner;
rotation = scr.rotation; rotation = scr.rotation;
@ -196,7 +191,7 @@ public class GuiScreenConfig extends WDScreen {
} }
private void clickSetRes() { private void clickSetRes() {
ScreenData scr = tes.getScreen(side); TileEntityScreen.Screen scr = tes.getScreen(side);
if(scr == null) if(scr == null)
return; //WHATDAFUQ? return; //WHATDAFUQ?

View File

@ -23,11 +23,9 @@ import net.montoyo.wd.miniserv.Constants;
import net.montoyo.wd.miniserv.client.*; import net.montoyo.wd.miniserv.client.*;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import net.montoyo.wd.utilities.serialization.Util;
import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.swing.filechooser.FileSystemView; import javax.swing.filechooser.FileSystemView;

View File

@ -15,14 +15,14 @@ import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.client.gui.controls.Button; import net.montoyo.wd.client.gui.controls.Button;
import net.montoyo.wd.client.gui.controls.TextField; import net.montoyo.wd.client.gui.controls.TextField;
import net.montoyo.wd.client.gui.loading.FillControl; import net.montoyo.wd.client.gui.loading.FillControl;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.item.ItemMinePad2; import net.montoyo.wd.item.ItemMinePad2;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageMinepadUrl; import net.montoyo.wd.net.server_bound.C2SMessageMinepadUrl;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
@ -32,7 +32,7 @@ import java.util.UUID;
public class GuiSetURL2 extends WDScreen { public class GuiSetURL2 extends WDScreen {
//Screen data //Screen data
private ScreenBlockEntity tileEntity; private TileEntityScreen tileEntity;
private BlockSide screenSide; private BlockSide screenSide;
private Vector3i remoteLocation; private Vector3i remoteLocation;
@ -55,7 +55,7 @@ public class GuiSetURL2 extends WDScreen {
@FillControl @FillControl
private Button btnOk; private Button btnOk;
public GuiSetURL2(ScreenBlockEntity tes, BlockSide side, String url, Vector3i rl) { public GuiSetURL2(TileEntityScreen tes, BlockSide side, String url, Vector3i rl) {
super(Component.nullToEmpty(null)); super(Component.nullToEmpty(null));
tileEntity = tes; tileEntity = tes;
screenSide = side; screenSide = side;
@ -120,7 +120,7 @@ public class GuiSetURL2 extends WDScreen {
if (!url.isEmpty()) { if (!url.isEmpty()) {
try { try {
ScreenBlockEntity.url(url); TileEntityScreen.url(url);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@ -8,6 +8,7 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
@ -26,10 +27,6 @@ import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageACQuery; import net.montoyo.wd.net.server_bound.C2SMessageACQuery;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.data.Bounds;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.io.IOException; import java.io.IOException;

View File

@ -1,273 +0,0 @@
package net.montoyo.wd.client.gui.camera;
import net.minecraft.client.Minecraft;
import net.minecraft.commands.arguments.EntityAnchorArgument;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.Vec2;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.ViewportEvent;
import net.minecraftforge.event.TickEvent;
import net.montoyo.wd.client.gui.GuiKeyboard;
import net.montoyo.wd.config.ClientConfig;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.entity.ScreenData;
import net.montoyo.wd.utilities.browser.WDBrowser;
import net.montoyo.wd.utilities.browser.handlers.js.queries.ElementCenterQuery;
import net.montoyo.wd.utilities.data.BlockSide;
public class KeyboardCamera {
private static ScreenBlockEntity tes;
private static BlockSide side;
private static double oxCrd = -1;
private static double xCrd = -1;
private static double nxCrd = -1;
private static double oyCrd = -1;
private static double yCrd = -1;
private static double nyCrd = -1;
private static double nextX = -1;
private static double nextY = -1;
private static double focalX = -1;
private static double focalY = -1;
private static final boolean[] mouseStatus = new boolean[2];
protected static Vec2 pxToHit(ScreenData scr, Vec2 dst) {
float cx, cy;
if (scr.rotation.isVertical) {
cy = dst.x;
cx = dst.y;
} else {
cx = dst.x;
cy = dst.y;
}
cx /= (float) scr.resolution.x;
cy /= (float) scr.resolution.y;
switch (scr.rotation) {
case ROT_270:
cx = 1.0f - cx;
break;
case ROT_180:
cx = 1.0f - cx;
cy = 1.0f - cy;
break;
case ROT_90:
cy = 1.0f - cy;
break;
}
if (side != BlockSide.BOTTOM)
cy = 1.0f - cy;
float swInverse = (((float) scr.size.x) - 4.f / 16.f);
float shInverse = (((float) scr.size.y) - 4.f / 16.f);
cx *= swInverse;
cy *= shInverse;
if (side.right.x > 0 || side.right.z > 0)
cx += 1.f;
if (side == BlockSide.TOP || side == BlockSide.BOTTOM)
cy -= 1.f;
return new Vec2(cx + (2 / 16f), cy + (2 / 16f));
}
protected static void updateCrd(ElementCenterQuery lock) {
ScreenData scr = tes.getScreen(side);
if (scr != null) {
Vec2 c;
if (!mouseStatus[0] && !mouseStatus[1]) {
if (lock.hasFocused()) {
if (ClientConfig.Input.keyboardCamera) {
nextX = lock.getX();
nextY = lock.getY();
c = pxToHit(scr, new Vec2((float) nextX, (float) nextY));
} else c = new Vec2(scr.size.x / 2f, scr.size.y / 2f);
} else c = new Vec2(scr.size.x / 2f, scr.size.y / 2f);
// } else c = new Vec2((float) focalX, (float) focalY);
} else return;
focalX = c.x;
focalY = c.y;
nextX = c.x;
nextY = c.y;
if (nextX < 0) nextX = 0;
else if (nextX > scr.size.x) nextX = scr.size.x;
if (nextY < 0) nextY = 0;
else if (nextY > scr.size.y) nextY = scr.size.y;
float scl = Math.max(scr.size.x, scr.size.y);
double mx = Minecraft.getInstance().mouseHandler.xpos();
mx /= Minecraft.getInstance().getWindow().getWidth();
double my = Minecraft.getInstance().mouseHandler.ypos();
my /= Minecraft.getInstance().getWindow().getHeight();
Vec2 v2 = new Vec2((float) mx, (float) my).add(-0.5f);
nextX += v2.x * scl;
nextY -= v2.y * scl;
}
}
protected static void pollElement() {
ScreenBlockEntity teTmp = tes;
BlockSide sdTmp = side;
// async nonsense can occur here
if (teTmp == null || sdTmp == null) return;
ScreenData scr = teTmp.getScreen(sdTmp);
if (scr != null) {
if (scr.browser instanceof WDBrowser wdBrowser) {
wdBrowser.focusedElement().dispatch(scr.browser);
updateCrd(((WDBrowser) scr.browser).focusedElement());
}
}
}
public static float[] getAngle(Entity e, double pct) {
BlockEntity tes = KeyboardCamera.tes;
BlockSide side = KeyboardCamera.side;
if (tes == null) return new float[]{Float.NaN, 0};
if (side == null) return new float[]{Float.NaN, 0};
double coxCrd = Mth.lerp(0.5 * pct, oxCrd, xCrd);
double coyCrd = Mth.lerp(0.5 * pct, oyCrd, yCrd);
double focalX = tes.getBlockPos().getX() +
side.right.x * (coxCrd - 1) + side.up.x * coyCrd + Math.abs(side.forward.x) * 0.5;
double focalY = tes.getBlockPos().getY() +
side.right.y * (coxCrd - 1) + side.up.y * coyCrd + Math.abs(side.forward.y) * 0.5;
double focalZ = tes.getBlockPos().getZ() +
side.right.z * (coxCrd - 1) + side.up.z * coyCrd + Math.abs(side.forward.z) * 0.5;
focalX += side.forward.x * 0.5f;
focalY += side.forward.y * 0.5f;
focalZ += side.forward.z * 0.5f;
float[] angle = lookAt(
e, EntityAnchorArgument.Anchor.EYES,
new Vec3(focalX, focalY, focalZ)
);
return angle;
}
public static void setMouse(int side, boolean pressed) {
mouseStatus[side] = pressed;
}
public static void updateCamera(ViewportEvent.ComputeCameraAngles event) {
if (tes == null) {
xCrd = -1;
yCrd = -1;
return; // nothing to do
}
if (xCrd == -1) return;
if (yCrd == -1) return;
float[] angle = getAngle(event.getCamera().getEntity(), event.getPartialTick());
if (Float.isNaN(angle[0])) return;
// float xRot = event.getYaw(); // left right
// float yRot = event.getPitch(); // up down
// TODO: smooth in/out
event.setYaw(angle[1]);
event.setPitch(angle[0]);
}
public static void focus(ScreenBlockEntity screen, BlockSide side) {
KeyboardCamera.tes = screen;
KeyboardCamera.side = side;
}
public static float[] lookAt(Entity entity, EntityAnchorArgument.Anchor pAnchor, Vec3 pTarget) {
Vec3 vec3 = pAnchor.apply(entity);
double d0 = pTarget.x - vec3.x;
double d1 = pTarget.y - vec3.y;
double d2 = pTarget.z - vec3.z;
double d3 = Math.sqrt(d0 * d0 + d2 * d2);
float xr = (Mth.wrapDegrees((float) (-(Mth.atan2(d1, d3) * (double) (180F / (float) Math.PI)))));
float yr = (Mth.wrapDegrees((float) (Mth.atan2(d2, d0) * (double) (180F / (float) Math.PI)) - 90.0F));
return new float[]{xr, yr};
}
protected static int delay = 8;
public static void gameTick(TickEvent.ClientTickEvent event) {
if (mouseStatus[0] || mouseStatus[1]) {
oxCrd = Mth.lerp(0.5, oxCrd, xCrd);
oyCrd = Mth.lerp(0.5, oyCrd, yCrd);
return;
}
if (event.phase.equals(TickEvent.Phase.END)) {
if (side == null) {
delay = 1;
oxCrd = -1;
oyCrd = -1;
xCrd = -1;
yCrd = -1;
nxCrd = -1;
nyCrd = -1;
return;
}
if (!(Minecraft.getInstance().screen instanceof GuiKeyboard)) {
tes = null;
side = null;
return;
}
pollElement();
double anxx = nextX;
double anxy = nextY;
if (
anxx == -1 || anxy == -1 ||
nxCrd == -1 || nyCrd == -1 ||
oxCrd == -1 || oyCrd == -1 ||
xCrd == -1 || yCrd == -1
) {
ScreenData data = tes.getScreen(side);
if (data == null)
return;
anxx = data.size.x / 2.0;
anxy = data.size.y / 2.0;
if (nxCrd == -1) {
oxCrd = xCrd = anxx;
oyCrd = yCrd = anxy;
}
}
nxCrd = anxx;
nyCrd = anxy;
oxCrd = Mth.lerp(0.5, oxCrd, xCrd);
xCrd = Mth.lerp(0.15, xCrd, nxCrd);
oyCrd = Mth.lerp(0.5, oyCrd, yCrd);
yCrd = Mth.lerp(0.15, yCrd, nyCrd);
}
}
}

View File

@ -14,18 +14,20 @@ import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.ShaderInstance;
import net.minecraft.client.resources.language.I18n; import net.minecraft.client.resources.language.I18n;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.WDScreen; import net.montoyo.wd.client.gui.WDScreen;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import net.montoyo.wd.utilities.data.Bounds; import net.montoyo.wd.utilities.Bounds;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import java.util.Arrays; import java.util.Arrays;
import static com.mojang.math.Axis.XP; import static com.mojang.math.Axis.XP;
import static org.lwjgl.opengl.GL11.*;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public abstract class Control { public abstract class Control {

View File

@ -7,14 +7,18 @@ package net.montoyo.wd.client.gui.controls;
import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.blaze3d.vertex.VertexFormat;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.GuiGraphics;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import net.montoyo.wd.utilities.data.Bounds; import net.montoyo.wd.utilities.Bounds;
import org.lwjgl.opengl.GL11;
import java.util.Arrays; import java.util.Arrays;
import static org.lwjgl.opengl.GL11.*;
public class ControlGroup extends Container { public class ControlGroup extends Container {
private int width; private int width;

View File

@ -6,7 +6,7 @@ package net.montoyo.wd.client.gui.controls;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.montoyo.wd.client.gui.loading.JsonOWrapper; import net.montoyo.wd.client.gui.loading.JsonOWrapper;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import net.montoyo.wd.utilities.VideoType; import net.montoyo.wd.utilities.VideoType;
import java.net.MalformedURLException; import java.net.MalformedURLException;

View File

@ -16,9 +16,10 @@ import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.ClientProxy; import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.registry.ItemRegistry; import net.montoyo.wd.init.ItemInit;
import net.montoyo.wd.item.ItemLaserPointer; import net.montoyo.wd.item.ItemLaserPointer;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import static com.mojang.math.Axis.*; import static com.mojang.math.Axis.*;
@ -39,7 +40,7 @@ public final class LaserPointerRenderer implements IItemRenderer {
ClientProxy.mouseOn || ClientProxy.mouseOn ||
ItemLaserPointer.isOn() ItemLaserPointer.isOn()
) && ) &&
mc.player.getItemInHand(InteractionHand.MAIN_HAND).getItem().equals(ItemRegistry.LASER_POINTER.get()) && mc.player.getItemInHand(InteractionHand.MAIN_HAND).getItem().equals(ItemInit.LASER_POINTER.get()) &&
(mc.hitResult == null || mc.hitResult.getType() == HitResult.Type.BLOCK || mc.hitResult.getType() == HitResult.Type.MISS); (mc.hitResult == null || mc.hitResult.getType() == HitResult.Type.BLOCK || mc.hitResult.getType() == HitResult.Type.MISS);
} }

View File

@ -19,9 +19,9 @@ import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.client.model.data.ModelData; import net.minecraftforge.client.model.data.ModelData;
import net.minecraftforge.client.model.data.ModelProperty; import net.minecraftforge.client.model.data.ModelProperty;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.math.Vector3f; import net.montoyo.wd.utilities.Vector3f;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;

View File

@ -7,27 +7,26 @@ package net.montoyo.wd.client.renderers;
import com.cinemamod.mcef.MCEFBrowser; import com.cinemamod.mcef.MCEFBrowser;
import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*; import com.mojang.blaze3d.vertex.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.remote.IWDBrowser;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.utilities.Vector3f;
import net.montoyo.wd.utilities.math.Vector3f; import net.montoyo.wd.utilities.Vector3i;
import net.montoyo.wd.utilities.math.Vector3i;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.lwjgl.opengl.GL11;
import static com.mojang.math.Axis.*; import static com.mojang.math.Axis.*;
public class ScreenRenderer implements BlockEntityRenderer<ScreenBlockEntity> { public class ScreenRenderer implements BlockEntityRenderer<TileEntityScreen> {
public ScreenRenderer() { public ScreenRenderer() {
} }
public static class ScreenRendererProvider implements BlockEntityRendererProvider<ScreenBlockEntity> { public static class ScreenRendererProvider implements BlockEntityRendererProvider<TileEntityScreen> {
@Override @Override
public @NotNull BlockEntityRenderer<ScreenBlockEntity> create(@NotNull Context arg) { public @NotNull BlockEntityRenderer<TileEntityScreen> create(@NotNull Context arg) {
return new ScreenRenderer(); return new ScreenRenderer();
} }
} }
@ -37,22 +36,19 @@ public class ScreenRenderer implements BlockEntityRenderer<ScreenBlockEntity> {
private final Vector3f tmpf = new Vector3f(); private final Vector3f tmpf = new Vector3f();
@Override @Override
public void render(ScreenBlockEntity te, float partialTick, @NotNull PoseStack poseStack, @NotNull MultiBufferSource bufferSource, int packedLight, int packedOverlay) { public void render(TileEntityScreen te, float partialTick, @NotNull PoseStack poseStack, @NotNull MultiBufferSource bufferSource, int packedLight, int packedOverlay) {
if (!te.isLoaded()) if (!te.isLoaded())
return; return;
//Disable lighting //Disable lighting
// RenderSystem.enableTexture(); // RenderSystem.enableTexture();
// RenderSystem.disableCull(); // RenderSystem.disableCull();
RenderSystem.disableBlend(); RenderSystem.disableBlend();
for (int i = 0; i < te.screenCount(); i++) { for (int i = 0; i < te.screenCount(); i++) {
ScreenData scr = te.getScreen(i); TileEntityScreen.Screen scr = te.getScreen(i);
if (scr.browser == null) { if (scr.browser == null) {
double dist = WebDisplays.PROXY.distanceTo(te, Minecraft.getInstance().getEntityRenderDispatcher().camera.getPosition()); scr.createBrowser(false, true);
if (dist <= WebDisplays.INSTANCE.loadDistance2 * 16)
scr.createBrowser(te, true);
else continue;
} }
// TODO: manually backface cull the screens // TODO: manually backface cull the screens
@ -125,7 +121,7 @@ public class ScreenRenderer implements BlockEntityRenderer<ScreenBlockEntity> {
//TODO: don't use tesselator //TODO: don't use tesselator
RenderSystem.enableDepthTest(); RenderSystem.enableDepthTest();
RenderSystem.setShader(GameRenderer::getPositionTexColorShader); RenderSystem.setShader(GameRenderer::getPositionTexColorShader);
RenderSystem._setShaderTexture(0, ((MCEFBrowser) scr.browser).getRenderer().getTextureID()); RenderSystem._setShaderTexture(0, ((IWDBrowser) scr.browser).getRenderer().getTextureID());
RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f); RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR); builder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX_COLOR);
builder.vertex(poseStack.last().pose(), -sw, -sh, 0.505f).uv(0.f, 1.f).color(1.f, 1.f, 1.f, 1.f).endVertex(); builder.vertex(poseStack.last().pose(), -sw, -sh, 0.505f).uv(0.f, 1.f).color(1.f, 1.f, 1.f, 1.f).endVertex();

View File

@ -38,7 +38,7 @@ public class ClientConfig {
"Due to how web browsers work however, the larger this value is, the smaller text is", "Due to how web browsers work however, the larger this value is, the smaller text is",
"Also, higher values will invariably lag more", "Also, higher values will invariably lag more",
"A good goto value for this would be the height of your monitor, in pixels", "A good goto value for this would be the height of your monitor, in pixels",
"A standard monitor is (at least currently) 1080", "A standard monitor is (at least currently) 1080"
}) })
@Translation("config.webdisplays.pad_res") @Translation("config.webdisplays.pad_res")
@IntRange(minV = 0, maxV = Integer.MAX_VALUE) @IntRange(minV = 0, maxV = Integer.MAX_VALUE)
@ -54,69 +54,54 @@ public class ClientConfig {
@Default(valueBoolean = true) @Default(valueBoolean = true)
public static boolean sidePad = true; public static boolean sidePad = true;
@Comment({ @Name("switch_buttons")
"Options relating to input handling" @Comment("If the left and right buttons should be swapped when using a laser")
}) @Translation("config.webdisplays.switch_buttons")
@CFGSegment("input") @DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
public static class Input { @Default(valueD = 30)
@Name("keyboard_camera") public static boolean switchButtons = true;
@Comment({
"If this is on, then the camera will try to focus on the selected element while a keyboard is in use",
"Elsewise, it'll try to focus on the center of the screen",
})
@Translation("config.webdisplays.keyboard_camera")
@Default(valueBoolean = true)
public static boolean keyboardCamera = true;
@Name("switch_buttons") @Comment({
@Comment("If the left and right buttons should be swapped when using a laser") "AutoVolume makes audio fade off based on distance",
@Translation("config.webdisplays.switch_buttons") "Currently, this seems to not work"
})
@CFGSegment("auto_volume")
public static class AutoVolumeControl {
@Name("enabled")
@Comment("Whether or not auto volume should be enabled")
@Translation("config.webdisplays.auto_vol")
@Default(valueBoolean = true)
public static boolean enableAutoVolume = true;
@Name("youtube_volume")
@Comment("How loud youtube should be by default")
@Translation("config.webdisplays.yt_vol")
@DoubleRange(minV = 0, maxV = 100)
@Default(valueD = 100)
public static double ytVolume = 100.0;
@Name("dist0")
@Comment("Distance after which you can't hear anything (in blocks)")
@Translation("config.webdisplays.d0")
@DoubleRange(minV = 0, maxV = Double.MAX_VALUE) @DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
@Default(valueD = 30) @Default(valueD = 30)
public static boolean switchButtons = true; public static double dist0 = 30.0;
}
// @Comment({ @Name("dist100")
// "AutoVolume makes audio fade off based on distance", @Comment("Distance after which the sound starts dropping (in blocks)")
// "Currently, this seems to not work" @Translation("config.webdisplays.d100")
// }) @DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
// @CFGSegment("auto_volume") @Default(valueD = 10)
// public static class AutoVolumeControl { public static double dist100 = 10.0;
// @Name("enabled") }
// @Comment("Whether or not auto volume should be enabled")
// @Translation("config.webdisplays.auto_vol")
// @Default(valueBoolean = true)
// public static boolean enableAutoVolume = true;
//
// @Name("youtube_volume")
// @Comment("How loud youtube should be by default")
// @Translation("config.webdisplays.yt_vol")
// @DoubleRange(minV = 0, maxV = 100)
// @Default(valueD = 100)
// public static double ytVolume = 100.0;
//
// @Name("dist0")
// @Comment("Distance after which you can't hear anything (in blocks)")
// @Translation("config.webdisplays.d0")
// @DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
// @Default(valueD = 30)
// public static double dist0 = 30.0;
//
// @Name("dist100")
// @Comment("Distance after which the sound starts dropping (in blocks)")
// @Translation("config.webdisplays.d100")
// @DoubleRange(minV = 0, maxV = Double.MAX_VALUE)
// @Default(valueD = 10)
// public static double dist100 = 10.0;
// }
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static void postLoad() { public static void postLoad() {
if (unloadDistance < loadDistance + 2.0) if (unloadDistance < loadDistance + 2.0)
unloadDistance = loadDistance + 2.0; unloadDistance = loadDistance + 2.0;
// if (AutoVolumeControl.dist0 < AutoVolumeControl.dist100 + 0.1) if (AutoVolumeControl.dist0 < AutoVolumeControl.dist100 + 0.1)
// AutoVolumeControl.dist0 = AutoVolumeControl.dist100 + 0.1; AutoVolumeControl.dist0 = AutoVolumeControl.dist100 + 0.1;
// cache pad resolution // cache pad resolution
WebDisplays.INSTANCE.padResY = padResolution; WebDisplays.INSTANCE.padResY = padResolution;
@ -126,8 +111,8 @@ public class ClientConfig {
WebDisplays.INSTANCE.unloadDistance2 = unloadDistance * unloadDistance; WebDisplays.INSTANCE.unloadDistance2 = unloadDistance * unloadDistance;
WebDisplays.INSTANCE.loadDistance2 = loadDistance * loadDistance; WebDisplays.INSTANCE.loadDistance2 = loadDistance * loadDistance;
// WebDisplays.INSTANCE.ytVolume = (float) AutoVolumeControl.ytVolume; WebDisplays.INSTANCE.ytVolume = (float) AutoVolumeControl.ytVolume;
// WebDisplays.INSTANCE.avDist100 = (float) AutoVolumeControl.dist100; WebDisplays.INSTANCE.avDist100 = (float) AutoVolumeControl.dist100;
// WebDisplays.INSTANCE.avDist0 = (float) AutoVolumeControl.dist0; WebDisplays.INSTANCE.avDist0 = (float) AutoVolumeControl.dist0;
} }
} }

View File

@ -22,15 +22,10 @@ public class CommonConfig {
@Name("hard_recipes") @Name("hard_recipes")
@Comment("If true, breaking the minePad is required to craft upgrades.") @Comment("If true, breaking the minePad is required to craft upgrades.")
@Translation("config.webdisplays.hard_recipes") @Translation("config.webdisplays.hard_recipes")
@IntRange(minV = 0, maxV = Integer.MAX_VALUE)
@Default(valueBoolean = true) @Default(valueBoolean = true)
public static boolean hardRecipes = true; public static boolean hardRecipes = true;
@Name("join_message")
@Comment("Whether or not webdisplays should thank the user for using the mod")
@Translation("config.webdisplays.join_message")
@Default(valueBoolean = true)
public static boolean joinMessage = true;
@Name("disable_ownership_thief") @Name("disable_ownership_thief")
@Comment("If true, the ownership thief item will be disabled") @Comment("If true, the ownership thief item will be disabled")
@Translation("config.webdisplays.disable_thief") @Translation("config.webdisplays.disable_thief")

View File

@ -8,8 +8,8 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import java.util.Objects; import java.util.Objects;
import java.util.function.Function; import java.util.function.Function;
@ -22,9 +22,9 @@ public abstract class ScreenControl {
} }
public abstract void write(FriendlyByteBuf buf); public abstract void write(FriendlyByteBuf buf);
public abstract void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException; public abstract void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException;
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public abstract void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx); public abstract void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx);
public void checkPerms(int perms, Function<Integer, Boolean> checker, ServerPlayer player) throws MissingPermissionException { public void checkPerms(int perms, Function<Integer, Boolean> checker, ServerPlayer player) throws MissingPermissionException {
if (!checker.apply(perms)) { if (!checker.apply(perms)) {

View File

@ -8,8 +8,8 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.fml.loading.FMLEnvironment; import net.minecraftforge.fml.loading.FMLEnvironment;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.builtin.*; import net.montoyo.wd.controls.builtin.*;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -32,7 +32,7 @@ public class ScreenControlRegistry {
if (FMLEnvironment.dist.isClient()) { if (FMLEnvironment.dist.isClient()) {
boolean shouldThrow = false; boolean shouldThrow = false;
try { try {
Method m = type.clazz.getMethod("handleClient", BlockPos.class, BlockSide.class, ScreenBlockEntity.class, NetworkEvent.Context.class); Method m = type.clazz.getMethod("handleClient", BlockPos.class, BlockSide.class, TileEntityScreen.class, NetworkEvent.Context.class);
OnlyIn onlyIn = m.getAnnotation(OnlyIn.class); OnlyIn onlyIn = m.getAnnotation(OnlyIn.class);
if (onlyIn == null) shouldThrow = true; if (onlyIn == null) shouldThrow = true;
Dist d = onlyIn.value(); // idc if this throws, lol Dist d = onlyIn.value(); // idc if this throws, lol

View File

@ -9,8 +9,8 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import java.util.function.Function; import java.util.function.Function;
@ -35,7 +35,7 @@ public class AutoVolumeControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
// I feel like there's probably a better permission category // I feel like there's probably a better permission category
checkPerms(ScreenRights.MANAGE_UPGRADES, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.MANAGE_UPGRADES, permissionChecker, ctx.getSender());
tes.setAutoVolume(side, autoVol); tes.setAutoVolume(side, autoVol);
@ -43,7 +43,7 @@ public class AutoVolumeControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
tes.setAutoVolume(side, autoVol); tes.setAutoVolume(side, autoVol);
} }
} }

View File

@ -8,9 +8,9 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.math.Vector2i; import net.montoyo.wd.utilities.Vector2i;
import java.util.function.Function; import java.util.function.Function;
@ -47,13 +47,13 @@ public class ClickControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
throw new RuntimeException("Cannot call click control on server"); throw new RuntimeException("Cannot call click control on server");
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
if (coord != null) if (coord != null)
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, coord, -1); tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, coord, -1);

View File

@ -10,8 +10,9 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.JSServerRequest; import net.montoyo.wd.core.JSServerRequest;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Log;
import java.util.function.Function; import java.util.function.Function;
@ -48,7 +49,7 @@ public class JSRequestControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
ServerPlayer player = ctx.getSender(); ServerPlayer player = ctx.getSender();
// if (reqType == null || data == null) Log.warning("Caught invalid JS request from player %s (UUID %s)", player.getName(), player.getGameProfile().getId().toString()); // if (reqType == null || data == null) Log.warning("Caught invalid JS request from player %s (UUID %s)", player.getName(), player.getGameProfile().getId().toString());
// else tes.handleJSRequest(player, side, reqId, reqType, data); // else tes.handleJSRequest(player, side, reqId, reqType, data);
@ -56,7 +57,7 @@ public class JSRequestControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
throw new RuntimeException("TODO"); throw new RuntimeException("TODO");
} }
} }

View File

@ -9,8 +9,8 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import java.util.function.Function; import java.util.function.Function;
@ -39,14 +39,14 @@ public class KeyTypedControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
checkPerms(ScreenRights.INTERACT, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.INTERACT, permissionChecker, ctx.getSender());
tes.type(side, text, soundPos, ctx.getSender()); tes.type(side, text, soundPos, ctx.getSender());
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
tes.type(side, text, soundPos); tes.type(side, text, soundPos);
} }
} }

View File

@ -9,9 +9,9 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.math.Vector2i; import net.montoyo.wd.utilities.Vector2i;
import java.util.function.Function; import java.util.function.Function;
@ -54,7 +54,7 @@ public class LaserControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
// feel like this makes sense, but I wanna get opinions first // feel like this makes sense, but I wanna get opinions first
// checkPerms(ScreenRights.INTERACT, permissionChecker, ctx.getSender()); // checkPerms(ScreenRights.INTERACT, permissionChecker, ctx.getSender());
ServerPlayer sender = ctx.getSender(); ServerPlayer sender = ctx.getSender();
@ -67,7 +67,7 @@ public class LaserControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
if (coord != null) if (coord != null)
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, coord, -1); tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, coord, -1);

View File

@ -11,9 +11,8 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.data.BlockSide;
import java.util.function.Function; import java.util.function.Function;
@ -80,7 +79,7 @@ public class ManageRightsAndUpdgradesControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
ServerPlayer player = ctx.getSender(); ServerPlayer player = ctx.getSender();
switch (type) { switch (type) {
case UPGRADES -> { case UPGRADES -> {
@ -90,7 +89,7 @@ public class ManageRightsAndUpdgradesControl extends ScreenControl {
else tes.removeUpgrade(side, toRemove, player); else tes.removeUpgrade(side, toRemove, player);
} }
case RIGHTS -> { case RIGHTS -> {
ScreenData scr = tes.getScreen(side); TileEntityScreen.Screen scr = tes.getScreen(side);
int fr = scr.owner.uuid.equals(player.getGameProfile().getId()) ? friendRights : scr.friendRights; int fr = scr.owner.uuid.equals(player.getGameProfile().getId()) ? friendRights : scr.friendRights;
int or = (scr.rightsFor(player) & ScreenRights.MANAGE_OTHER_RIGHTS) == 0 ? scr.otherRights : otherRights; int or = (scr.rightsFor(player) & ScreenRights.MANAGE_OTHER_RIGHTS) == 0 ? scr.otherRights : otherRights;
@ -103,7 +102,7 @@ public class ManageRightsAndUpdgradesControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
ServerPlayer player = ctx.getSender(); ServerPlayer player = ctx.getSender();
switch (type) { switch (type) {
case UPGRADES -> { case UPGRADES -> {
@ -112,7 +111,7 @@ public class ManageRightsAndUpdgradesControl extends ScreenControl {
else tes.removeUpgrade(side, toRemove, player); else tes.removeUpgrade(side, toRemove, player);
} }
case RIGHTS -> { case RIGHTS -> {
ScreenData scr = tes.getScreen(side); TileEntityScreen.Screen scr = tes.getScreen(side);
int fr = friendRights; int fr = friendRights;
int or = otherRights; int or = otherRights;

View File

@ -10,9 +10,9 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.serialization.NameUUIDPair; import net.montoyo.wd.utilities.NameUUIDPair;
import java.util.function.Function; import java.util.function.Function;
@ -41,7 +41,7 @@ public class ModifyFriendListControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
ServerPlayer player = ctx.getSender(); ServerPlayer player = ctx.getSender();
checkPerms(ScreenRights.MANAGE_FRIEND_LIST, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.MANAGE_FRIEND_LIST, permissionChecker, ctx.getSender());
if (adding) tes.addFriend(player, side, friend); if (adding) tes.addFriend(player, side, friend);
@ -50,7 +50,7 @@ public class ModifyFriendListControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
throw new RuntimeException("TODO"); throw new RuntimeException("TODO");
} }
} }

View File

@ -8,9 +8,9 @@ import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.NetworkEvent; import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.serialization.NameUUIDPair; import net.montoyo.wd.utilities.NameUUIDPair;
import java.util.function.Function; import java.util.function.Function;
@ -35,13 +35,13 @@ public class OwnerControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
throw new RuntimeException("Cannot handle ownership theft packet from server"); throw new RuntimeException("Cannot handle ownership theft packet from server");
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
tes.getScreen(side).owner = owner; tes.getScreen(side).owner = owner;
} }
} }

View File

@ -9,10 +9,10 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.data.Rotation; import net.montoyo.wd.utilities.Rotation;
import net.montoyo.wd.utilities.math.Vector2i; import net.montoyo.wd.utilities.Vector2i;
import java.util.function.Function; import java.util.function.Function;
@ -55,7 +55,7 @@ public class ScreenModifyControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
checkPerms(ScreenRights.MODIFY_SCREEN, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.MODIFY_SCREEN, permissionChecker, ctx.getSender());
switch (type) { switch (type) {
case RESOLUTION -> tes.setResolution(side, res); case RESOLUTION -> tes.setResolution(side, res);
@ -65,7 +65,7 @@ public class ScreenModifyControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
switch (type) { switch (type) {
case RESOLUTION -> tes.setResolution(side, res); case RESOLUTION -> tes.setResolution(side, res);
case ROTATION -> tes.setRotation(side, rotation); case ROTATION -> tes.setRotation(side, rotation);

View File

@ -9,9 +9,9 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
import java.util.function.Function; import java.util.function.Function;
@ -41,7 +41,7 @@ public class SetURLControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
// TODO: deal with remote // TODO: deal with remote
checkPerms(ScreenRights.CHANGE_URL, permissionChecker, ctx.getSender()); checkPerms(ScreenRights.CHANGE_URL, permissionChecker, ctx.getSender());
try { try {
@ -53,7 +53,7 @@ public class SetURLControl extends ScreenControl {
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
try { try {
tes.setScreenURL(side, url); tes.setScreenURL(side, url);
} catch (Throwable err) { } catch (Throwable err) {

View File

@ -9,8 +9,9 @@ import net.minecraftforge.network.NetworkEvent;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.controls.ScreenControl; import net.montoyo.wd.controls.ScreenControl;
import net.montoyo.wd.core.MissingPermissionException; import net.montoyo.wd.core.MissingPermissionException;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.NameUUIDPair;
import java.util.function.Function; import java.util.function.Function;
@ -28,13 +29,13 @@ public class TurnOffControl extends ScreenControl {
} }
@Override @Override
public void handleServer(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException { public void handleServer(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx, Function<Integer, Boolean> permissionChecker) throws MissingPermissionException {
throw new RuntimeException("Cannot handle deactivation packet from server"); throw new RuntimeException("Cannot handle deactivation packet from server");
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void handleClient(BlockPos pos, BlockSide side, ScreenBlockEntity tes, NetworkEvent.Context ctx) { public void handleClient(BlockPos pos, BlockSide side, TileEntityScreen tes, NetworkEvent.Context ctx) {
if (side != null) { if (side != null) {
WebDisplays.PROXY.closeGui(pos, side); WebDisplays.PROXY.closeGui(pos, side);
tes.disableScreen(side); tes.disableScreen(side);

View File

@ -0,0 +1,24 @@
/*
* Copyright (C) 2018 BARBOTIN Nicolas
*/
package net.montoyo.wd.core;
public enum AdvancementIcon {
WEB_DISPLAYS("wd"),
BROKEN_PAD("brokenpad"),
PIGEON("pigeon");
private final String name;
AdvancementIcon(String n) {
name = n;
}
@Override
public String toString() {
return name;
}
}

View File

@ -7,7 +7,6 @@ package net.montoyo.wd.core;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
// TODO: bring this back when SSR is implemented
public class CCArguments implements IComputerArgs { public class CCArguments implements IComputerArgs {
private final Object[] args; private final Object[] args;

View File

@ -5,7 +5,7 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.montoyo.wd.registry.ItemRegistry; import net.montoyo.wd.init.ItemInit;
public enum CraftComponent { public enum CraftComponent {
STONEKEY("stonekey", "StoneKey"), STONEKEY("stonekey", "StoneKey"),
@ -32,6 +32,6 @@ public enum CraftComponent {
} }
public ItemStack makeItemStack() { public ItemStack makeItemStack() {
return new ItemStack(ItemRegistry.getComputerCraftItem(ordinal()).get(), 1); return new ItemStack(ItemInit.getComputerCraftItem(ordinal()).get(), 1);
} }
} }

View File

@ -20,7 +20,9 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
public class Criterion implements CriterionTrigger<Criterion.Instance> { public class Criterion implements CriterionTrigger<Criterion.Instance> {
public static class Instance extends AbstractCriterionTriggerInstance { public static class Instance extends AbstractCriterionTriggerInstance {
public Instance(ResourceLocation id, ContextAwarePredicate arg2) { public Instance(ResourceLocation id, ContextAwarePredicate arg2) {
super(id, arg2); super(id, arg2);
} }
@ -65,9 +67,10 @@ public class Criterion implements CriterionTrigger<Criterion.Instance> {
public void trigger(PlayerAdvancements ply) { public void trigger(PlayerAdvancements ply) {
ArrayList<Listener<Instance>> listeners = map.get(ply); ArrayList<Listener<Instance>> listeners = map.get(ply);
if (listeners != null) { if(listeners != null) {
Listener[] copy = listeners.toArray(new Listener[0]); //We need to make a copy, otherwise we get a ConcurrentModificationException Listener[] copy = listeners.toArray(new Listener[0]); //We need to make a copy, otherwise we get a ConcurrentModificationException
Arrays.stream(copy).forEach(l -> l.run(ply)); Arrays.stream(copy).forEach(l -> l.run(ply));
} }
} }
} }

View File

@ -8,22 +8,23 @@ import net.minecraft.util.StringRepresentable;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.BlockEntityType;
import net.montoyo.wd.entity.KeyboardBlockEntity; import net.montoyo.wd.entity.TileEntityKeyboard;
import net.montoyo.wd.entity.RemoteControlBlockEntity; import net.montoyo.wd.entity.TileEntityRCtrl;
import net.montoyo.wd.entity.RedstoneControlBlockEntity; import net.montoyo.wd.entity.TileEntityRedCtrl;
import net.montoyo.wd.entity.ServerBlockEntity; import net.montoyo.wd.entity.TileEntityServer;
import net.montoyo.wd.registry.BlockRegistry; import net.montoyo.wd.init.BlockInit;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.util.function.Supplier; import java.util.function.Supplier;
public enum DefaultPeripheral implements StringRepresentable { public enum DefaultPeripheral implements StringRepresentable {
KEYBOARD("keyboard", "Keyboard", KeyboardBlockEntity::new, BlockRegistry.KEYBOARD_BLOCK), //WITH FACING (< 3)
KEYBOARD("keyboard", "Keyboard", TileEntityKeyboard::new, BlockInit.blockKeyBoard), //WITH FACING (< 3)
// CC_INTERFACE("ccinterface", "ComputerCraft_Interface", TileEntityCCInterface.class), // CC_INTERFACE("ccinterface", "ComputerCraft_Interface", TileEntityCCInterface.class),
// OC_INTERFACE("cointerface", "OpenComputers_Interface", TileEntityOCInterface.class), // OC_INTERFACE("cointerface", "OpenComputers_Interface", TileEntityOCInterface.class),
REMOTE_CONTROLLER("remotectrl", "Remote_Controller", RemoteControlBlockEntity::new , BlockRegistry.REMOTE_CONTROLLER_BLOCK), //WITHOUT FACING (>= 3) REMOTE_CONTROLLER("remotectrl", "Remote_Controller", TileEntityRCtrl::new ,BlockInit.blockRControl), //WITHOUT FACING (>= 3)
REDSTONE_CONTROLLER("redstonectrl", "Redstone_Controller", RedstoneControlBlockEntity::new , BlockRegistry.REDSTONE_CONTROL_BLOCK), REDSTONE_CONTROLLER("redstonectrl", "Redstone_Controller", TileEntityRedCtrl::new ,BlockInit.blockRedControl),
SERVER("server", "Server", ServerBlockEntity::new, BlockRegistry.SERVER_BLOCK); SERVER("server", "Server", TileEntityServer::new, BlockInit.blockServer);
private final String name; private final String name;
private final String wikiName; private final String wikiName;

View File

@ -5,7 +5,9 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
public enum HasAdvancement { public enum HasAdvancement {
DONT_KNOW, DONT_KNOW,
YES, YES,
NO NO
} }

View File

@ -7,8 +7,10 @@ package net.montoyo.wd.core;
import java.util.Map; import java.util.Map;
public interface IComputerArgs { public interface IComputerArgs {
String checkString(int i); String checkString(int i);
int checkInteger(int i); int checkInteger(int i);
Map checkTable(int i); Map checkTable(int i);
int count(); int count();
} }

View File

@ -7,9 +7,11 @@ package net.montoyo.wd.core;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
public interface IPeripheral { public interface IPeripheral {
boolean connect(Level world, BlockPos blockPos, BlockState blockState, Vector3i screenPos, BlockSide screenSide); boolean connect(Level world, BlockPos blockPos, BlockState blockState, Vector3i screenPos, BlockSide screenSide);
} }

View File

@ -6,12 +6,14 @@
// //
//import net.montoyo.mcef.api.IJSQueryCallback; //import net.montoyo.mcef.api.IJSQueryCallback;
//import net.montoyo.wd.entity.TileEntityScreen; //import net.montoyo.wd.entity.TileEntityScreen;
//import net.montoyo.wd.utilities.orientation.BlockSide; //import net.montoyo.wd.utilities.BlockSide;
// //
//import javax.annotation.Nonnull; //import javax.annotation.Nonnull;
// //
//public interface IScreenQueryHandler { //public interface IScreenQueryHandler {
//
// //args is an array of Doubles or Strings // //args is an array of Doubles or Strings
// //The screen DOES exist, so scr.getScreen(side) is never null // //The screen DOES exist, so scr.getScreen(side) is never null
// void handleQuery(@Nonnull IJSQueryCallback cb, @Nonnull TileEntityScreen scr, @Nonnull BlockSide side, @Nonnull Object[] args); // void handleQuery(@Nonnull IJSQueryCallback cb, @Nonnull TileEntityScreen scr, @Nonnull BlockSide side, @Nonnull Object[] args);
//
//} //}

View File

@ -6,15 +6,17 @@ package net.montoyo.wd.core;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public interface IUpgrade { public interface IUpgrade {
void onInstall(@Nonnull ScreenBlockEntity tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is);
boolean onRemove(@Nonnull ScreenBlockEntity tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is); //Return true to prevent dropping void onInstall(@Nonnull TileEntityScreen tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is);
boolean onRemove(@Nonnull TileEntityScreen tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is); //Return true to prevent dropping
boolean isSameUpgrade(@Nonnull ItemStack myStack, @Nonnull ItemStack otherStack); //myStack.getItem() is an instance of this class boolean isSameUpgrade(@Nonnull ItemStack myStack, @Nonnull ItemStack otherStack); //myStack.getItem() is an instance of this class
String getJSName(@Nonnull ItemStack is); //modname:upgradename String getJSName(@Nonnull ItemStack is); //modname:upgradename
} }

View File

@ -5,7 +5,9 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
public interface IWDDCapability { public interface IWDDCapability {
boolean isFirstRun(); boolean isFirstRun();
void clearFirstRun(); void clearFirstRun();
void cloneTo(IWDDCapability dst); void cloneTo(IWDDCapability dst);
} }

View File

@ -5,9 +5,10 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
public enum JSServerRequest { public enum JSServerRequest {
CLEAR_REDSTONE, CLEAR_REDSTONE,
SET_REDSTONE_AT(Integer.class, Integer.class, Boolean.class); SET_REDSTONE_AT(Integer.class, Integer.class, Boolean.class);
@ -49,4 +50,5 @@ public enum JSServerRequest {
return ret; return ret;
} }
} }

View File

@ -7,6 +7,7 @@ package net.montoyo.wd.core;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
public class MissingPermissionException extends Exception { public class MissingPermissionException extends Exception {
private final int permission; private final int permission;
private final ServerPlayer player; private final ServerPlayer player;
@ -23,4 +24,5 @@ public class MissingPermissionException extends Exception {
public ServerPlayer getPlayer() { public ServerPlayer getPlayer() {
return player; return player;
} }
} }

View File

@ -10,6 +10,7 @@ import java.util.Optional;
@Optional.Interface(iface = "net.montoyo.wd.core.IComputerArgs", modid = "opencomputers") @Optional.Interface(iface = "net.montoyo.wd.core.IComputerArgs", modid = "opencomputers")
public class OCArguments implements IComputerArgs { public class OCArguments implements IComputerArgs {
//Keep this as an "Object" so that it doesn't crash if OC is absent //Keep this as an "Object" so that it doesn't crash if OC is absent
private final Object args; private final Object args;
@ -40,4 +41,5 @@ public class OCArguments implements IComputerArgs {
public int count() { public int count() {
return ((Arguments) args).count(); return ((Arguments) args).count();
} }
} */ } */

View File

@ -5,10 +5,9 @@
package net.montoyo.wd.core; package net.montoyo.wd.core;
public abstract class ScreenRights { public abstract class ScreenRights {
public static final int CHANGE_URL = 1; //Change URL AND run JavaScript public static final int CHANGE_URL = 1; //Change URL AND run JavaScript
/** /** use {@link ScreenRights#INTERACT instead} */
* use {@link ScreenRights#INTERACT instead}
*/
@Deprecated(forRemoval = true) @Deprecated(forRemoval = true)
public static final int CLICK = 2; //Click AND type public static final int CLICK = 2; //Click AND type
public static final int INTERACT = 2; //Click AND type public static final int INTERACT = 2; //Click AND type
@ -22,4 +21,5 @@ public abstract class ScreenRights {
public static final int NONE = 0; public static final int NONE = 0;
public static final int ALL = 0xFF; public static final int ALL = 0xFF;
public static final int DEFAULTS = CHANGE_URL | INTERACT | MANAGE_UPGRADES | MODIFY_SCREEN; public static final int DEFAULTS = CHANGE_URL | INTERACT | MANAGE_UPGRADES | MODIFY_SCREEN;
} }

View File

@ -18,11 +18,14 @@ import javax.annotation.Nonnull;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
public class WDDCapability implements IWDDCapability { public class WDDCapability implements IWDDCapability {
public static class Factory implements Callable<IWDDCapability> { public static class Factory implements Callable<IWDDCapability> {
@Override @Override
public IWDDCapability call() { public IWDDCapability call() {
return new WDDCapability(); return new WDDCapability();
} }
} }
public static class Provider implements ICapabilitySerializable<CompoundTag> { public static class Provider implements ICapabilitySerializable<CompoundTag> {
@ -35,7 +38,7 @@ public class WDDCapability implements IWDDCapability {
@NotNull @NotNull
@Override @Override
public <T> LazyOptional<T> getCapability(@NotNull Capability<T> capability, @org.jetbrains.annotations.Nullable Direction arg) { public <T> LazyOptional<T> getCapability(@NotNull Capability<T> capability, @org.jetbrains.annotations.Nullable Direction arg) {
return cap == capability ? INSTANCE.cast() : LazyOptional.empty(); return cap == capability ? INSTANCE.cast() : LazyOptional.empty();
} }
@Override @Override
@ -75,7 +78,8 @@ public class WDDCapability implements IWDDCapability {
@Override @Override
public void cloneTo(IWDDCapability dst) { public void cloneTo(IWDDCapability dst) {
if (!isFirstRun()) if(!isFirstRun())
dst.clearFirstRun(); dst.clearFirstRun();
} }
} }

View File

@ -18,54 +18,53 @@ import java.util.HashMap;
import java.util.function.Supplier; import java.util.function.Supplier;
public abstract class GuiData { public abstract class GuiData {
public static GuiData read(String name, FriendlyByteBuf buf) { public static GuiData read(String name, FriendlyByteBuf buf) {
GuiType type = dataTable.get(name); GuiType type = dataTable.get(name);
GuiData data = type.create(); GuiData data = type.create();
data.deserialize(buf); data.deserialize(buf);
return data; return data;
} }
protected static class GuiType { protected static class GuiType {
Class<? extends GuiData> clazz; Class<? extends GuiData> clazz;
Supplier<GuiData> constructor; Supplier<GuiData> constructor;
public GuiType(Class<? extends GuiData> clazz, Supplier<GuiData> constructor) { public GuiType(Class<? extends GuiData> clazz, Supplier<GuiData> constructor) {
this.clazz = clazz; this.clazz = clazz;
this.constructor = constructor; this.constructor = constructor;
} }
public GuiData create() { public GuiData create() {
return constructor.get(); return constructor.get();
} }
} }
private static final HashMap<String, GuiType> dataTable = new HashMap<>(); private static final HashMap<String, GuiType> dataTable = new HashMap<>();
static { static {
dataTable.put("SetURL", new GuiType(SetURLData.class, SetURLData::new)); dataTable.put("SetURL", new GuiType(SetURLData.class, SetURLData::new));
dataTable.put("ScreenConfig", new GuiType(ScreenConfigData.class, ScreenConfigData::new)); dataTable.put("ScreenConfig", new GuiType(ScreenConfigData.class, ScreenConfigData::new));
dataTable.put("Keyboard", new GuiType(KeyboardData.class, KeyboardData::new)); dataTable.put("Keyboard", new GuiType(KeyboardData.class, KeyboardData::new));
dataTable.put("RedstoneCtrl", new GuiType(RedstoneCtrlData.class, RedstoneCtrlData::new)); dataTable.put("RedstoneCtrl", new GuiType(RedstoneCtrlData.class, RedstoneCtrlData::new));
dataTable.put("Server", new GuiType(ServerData.class, ServerData::new)); dataTable.put("Server", new GuiType(ServerData.class, ServerData::new));
} }
public static Class<? extends GuiData> classOf(String name) { public static Class<? extends GuiData> classOf(String name) {
return dataTable.get(name).clazz; return dataTable.get(name).clazz;
} }
public GuiData() { public GuiData() {
} }
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public abstract Screen createGui(Screen old, Level world); public abstract Screen createGui(Screen old, Level world);
public abstract String getName(); public abstract String getName();
public void sendTo(ServerPlayer player) { public void sendTo(ServerPlayer player) {
WDNetworkRegistry.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new S2CMessageOpenGui(this)); WDNetworkRegistry.INSTANCE.send(PacketDistributor.PLAYER.with(() -> player), new S2CMessageOpenGui(this));
} }
public abstract void serialize(FriendlyByteBuf buf); public abstract void serialize(FriendlyByteBuf buf);
public abstract void deserialize(FriendlyByteBuf buf); public abstract void deserialize(FriendlyByteBuf buf);
} }

View File

@ -12,12 +12,13 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.GuiKeyboard; import net.montoyo.wd.client.gui.GuiKeyboard;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
public class KeyboardData extends GuiData { public class KeyboardData extends GuiData {
public Vector3i pos; public Vector3i pos;
public BlockSide side; public BlockSide side;
public int kbX; public int kbX;
@ -27,7 +28,7 @@ public class KeyboardData extends GuiData {
public KeyboardData() { public KeyboardData() {
} }
public KeyboardData(ScreenBlockEntity tes, BlockSide side, BlockPos kbPos) { public KeyboardData(TileEntityScreen tes, BlockSide side, BlockPos kbPos) {
pos = new Vector3i(tes.getBlockPos()); pos = new Vector3i(tes.getBlockPos());
this.side = side; this.side = side;
kbX = kbPos.getX(); kbX = kbPos.getX();
@ -39,12 +40,12 @@ public class KeyboardData extends GuiData {
@Override @Override
public Screen createGui(Screen old, Level world) { public Screen createGui(Screen old, Level world) {
BlockEntity te = world.getBlockEntity(pos.toBlock()); BlockEntity te = world.getBlockEntity(pos.toBlock());
if (te == null || !(te instanceof ScreenBlockEntity)) { if(te == null || !(te instanceof TileEntityScreen)) {
Log.error("TileEntity at %s is not a screen; can't open keyboard!", pos.toString()); Log.error("TileEntity at %s is not a screen; can't open keyboard!", pos.toString());
return null; return null;
} }
return new GuiKeyboard((ScreenBlockEntity) te, side, new BlockPos(kbX, kbY, kbZ)); return new GuiKeyboard((TileEntityScreen) te, side, new BlockPos(kbX, kbY, kbZ));
} }
@Override @Override

View File

@ -13,9 +13,10 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.GuiRedstoneCtrl; import net.montoyo.wd.client.gui.GuiRedstoneCtrl;
import net.montoyo.wd.net.BufferUtils; import net.montoyo.wd.net.BufferUtils;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
public class RedstoneCtrlData extends GuiData { public class RedstoneCtrlData extends GuiData {
public ResourceLocation dimension; public ResourceLocation dimension;
public Vector3i pos; public Vector3i pos;
public String risingEdgeURL; public String risingEdgeURL;

View File

@ -13,28 +13,28 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.network.PacketDistributor; import net.minecraftforge.network.PacketDistributor;
import net.montoyo.wd.client.gui.GuiScreenConfig; import net.montoyo.wd.client.gui.GuiScreenConfig;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.net.BufferUtils; import net.montoyo.wd.net.BufferUtils;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.client_bound.S2CMessageOpenGui; import net.montoyo.wd.net.client_bound.S2CMessageOpenGui;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.serialization.NameUUIDPair; import net.montoyo.wd.utilities.NameUUIDPair;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
public class ScreenConfigData extends GuiData { public class ScreenConfigData extends GuiData {
public boolean onlyUpdate;
public Vector3i pos;
public BlockSide side;
public NameUUIDPair[] friends;
public int friendRights;
public int otherRights;
public ScreenConfigData() { public boolean onlyUpdate;
} public Vector3i pos;
public BlockSide side;
public NameUUIDPair[] friends;
public int friendRights;
public int otherRights;
public ScreenConfigData(Vector3i pos, BlockSide side, ScreenData scr) { public ScreenConfigData() {
}
public ScreenConfigData(Vector3i pos, BlockSide side, TileEntityScreen.Screen scr) {
this.pos = pos; this.pos = pos;
this.side = side; this.side = side;
friends = scr.friends.toArray(new NameUUIDPair[0]); friends = scr.friends.toArray(new NameUUIDPair[0]);
@ -63,12 +63,12 @@ public class ScreenConfigData extends GuiData {
return null; return null;
BlockEntity te = world.getBlockEntity(pos.toBlock()); BlockEntity te = world.getBlockEntity(pos.toBlock());
if (te == null || !(te instanceof ScreenBlockEntity)) { if (te == null || !(te instanceof TileEntityScreen)) {
Log.error("TileEntity at %s is not a screen; can't open gui!", pos.toString()); Log.error("TileEntity at %s is not a screen; can't open gui!", pos.toString());
return null; return null;
} }
return new GuiScreenConfig(Component.nullToEmpty(""), (ScreenBlockEntity) te, side, friends, friendRights, otherRights); return new GuiScreenConfig(Component.nullToEmpty(""), (TileEntityScreen) te, side, friends, friendRights, otherRights);
} }
@Override @Override

View File

@ -12,10 +12,11 @@ import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.GuiServer; import net.montoyo.wd.client.gui.GuiServer;
import net.montoyo.wd.net.BufferUtils; import net.montoyo.wd.net.BufferUtils;
import net.montoyo.wd.utilities.serialization.NameUUIDPair; import net.montoyo.wd.utilities.NameUUIDPair;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
public class ServerData extends GuiData { public class ServerData extends GuiData {
public Vector3i pos; public Vector3i pos;
public NameUUIDPair owner; public NameUUIDPair owner;

View File

@ -12,13 +12,14 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.OnlyIn;
import net.montoyo.wd.client.gui.GuiSetURL2; import net.montoyo.wd.client.gui.GuiSetURL2;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.net.BufferUtils; import net.montoyo.wd.net.BufferUtils;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
public class SetURLData extends GuiData { public class SetURLData extends GuiData {
public Vector3i pos; public Vector3i pos;
public BlockSide side; public BlockSide side;
public String url; public String url;
@ -49,12 +50,12 @@ public class SetURLData extends GuiData {
@Override @Override
public Screen createGui(Screen old, Level world) { public Screen createGui(Screen old, Level world) {
BlockEntity te = world.getBlockEntity(pos.toBlock()); BlockEntity te = world.getBlockEntity(pos.toBlock());
if (te == null || !(te instanceof ScreenBlockEntity)) { if(te == null || !(te instanceof TileEntityScreen)) {
Log.error("TileEntity at %s is not a screen; can't open gui!", pos.toString()); Log.error("TileEntity at %s is not a screen; can't open gui!", pos.toString());
return null; return null;
} }
return new GuiSetURL2((ScreenBlockEntity) te, side, url, isRemote ? remoteLocation : null); return new GuiSetURL2((TileEntityScreen) te, side, url, isRemote ? remoteLocation : null);
} }
@Override @Override

File diff suppressed because it is too large Load Diff

View File

@ -1,211 +0,0 @@
package net.montoyo.wd.entity;
import com.cinemamod.mcef.MCEF;
import com.cinemamod.mcef.MCEFBrowser;
import com.cinemamod.mcef.listeners.MCEFCursorChangeListener;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.config.CommonConfig;
import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.browser.InWorldQueries;
import net.montoyo.wd.utilities.browser.WDBrowser;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.math.Vector2i;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import org.cef.browser.CefBrowser;
import java.util.ArrayList;
import java.util.UUID;
public class ScreenData {
public BlockSide side;
public Vector2i size;
public Vector2i resolution;
public Rotation rotation = Rotation.ROT_0;
public String url;
protected VideoType videoType;
public NameUUIDPair owner;
public ArrayList<NameUUIDPair> friends;
public int friendRights;
public int otherRights;
public CefBrowser browser;
public ArrayList<ItemStack> upgrades;
public boolean doTurnOnAnim;
public long turnOnTime;
public Player laserUser;
public final Vector2i lastMousePos = new Vector2i();
public NibbleArray redstoneStatus; //null on client
public boolean autoVolume = true;
public int mouseType;
public static ScreenData deserialize(CompoundTag tag) {
ScreenData ret = new ScreenData();
ret.side = BlockSide.values()[tag.getByte("Side")];
ret.size = new Vector2i(tag.getInt("Width"), tag.getInt("Height"));
ret.resolution = new Vector2i(tag.getInt("ResolutionX"), tag.getInt("ResolutionY"));
ret.rotation = Rotation.values()[tag.getByte("Rotation")];
ret.url = tag.getString("URL");
ret.videoType = VideoType.getTypeFromURL(ret.url);
if (ret.resolution.x <= 0 || ret.resolution.y <= 0) {
float psx = ((float) ret.size.x) * 16.f - 4.f;
float psy = ((float) ret.size.y) * 16.f - 4.f;
psx *= 8.f; //TODO: Use ratio in config file
psy *= 8.f;
ret.resolution.x = (int) psx;
ret.resolution.y = (int) psy;
}
if (tag.contains("OwnerName")) {
String name = tag.getString("OwnerName");
UUID uuid = tag.getUUID("OwnerUUID");
ret.owner = new NameUUIDPair(name, uuid);
}
ListTag friends = tag.getList("Friends", 10);
ret.friends = new ArrayList<>(friends.size());
for (int i = 0; i < friends.size(); i++) {
CompoundTag nf = friends.getCompound(i);
NameUUIDPair pair = new NameUUIDPair(nf.getString("Name"), nf.getUUID("UUID"));
ret.friends.add(pair);
}
ret.friendRights = tag.getByte("FriendRights");
ret.otherRights = tag.getByte("OtherRights");
ListTag upgrades = tag.getList("Upgrades", 10);
ret.upgrades = new ArrayList<>();
for (int i = 0; i < upgrades.size(); i++)
ret.upgrades.add(ItemStack.of(upgrades.getCompound(i)));
if (tag.contains("AutoVolume"))
ret.autoVolume = tag.getBoolean("AutoVolume");
return ret;
}
public CompoundTag serialize() {
CompoundTag tag = new CompoundTag();
tag.putByte("Side", (byte) side.ordinal());
tag.putInt("Width", size.x);
tag.putInt("Height", size.y);
tag.putInt("ResolutionX", resolution.x);
tag.putInt("ResolutionY", resolution.y);
tag.putByte("Rotation", (byte) rotation.ordinal());
tag.putString("URL", url);
if (owner == null)
Log.warning("Found TES with NO OWNER!!");
else {
tag.putString("OwnerName", owner.name);
tag.putUUID("OwnerUUID", owner.uuid);
}
ListTag list = new ListTag();
for (NameUUIDPair f : friends) {
CompoundTag nf = new CompoundTag();
nf.putString("Name", f.name);
nf.putUUID("UUID", f.uuid);
list.add(nf);
}
tag.put("Friends", list);
tag.putByte("FriendRights", (byte) friendRights);
tag.putByte("OtherRights", (byte) otherRights);
list = new ListTag();
for (ItemStack is : upgrades)
list.add(is.save(new CompoundTag()));
tag.put("Upgrades", list);
tag.putBoolean("AutoVolume", autoVolume);
return tag;
}
public int rightsFor(Player ply) {
return rightsFor(ply.getGameProfile().getId());
}
public int rightsFor(UUID uuid) {
if (owner.uuid.equals(uuid))
return ScreenRights.ALL;
return friends.stream().anyMatch(f -> f.uuid.equals(uuid)) ? friendRights : otherRights;
}
public void setupRedstoneStatus(Level world, BlockPos start) {
if (world.isClientSide()) {
Log.warning("Called Screen.setupRedstoneStatus() on client.");
return;
}
if (redstoneStatus != null) {
Log.warning("Called Screen.setupRedstoneStatus() on server, but redstone status is non-null");
return;
}
Direction[] VALUES = Direction.values();
redstoneStatus = new NibbleArray(size.x * size.y);
final Direction facing = VALUES[side.reverse().ordinal()];
final ScreenIterator it = new ScreenIterator(start, side, size);
while (it.hasNext()) {
int idx = it.getIndex();
redstoneStatus.set(idx, world.getSignal(it.next(), facing));
}
}
public void clampResolution() {
if (resolution.x > CommonConfig.Screen.maxResolutionX) {
float newY = ((float) resolution.y) * ((float) CommonConfig.Screen.maxResolutionX) / ((float) resolution.x);
resolution.x = CommonConfig.Screen.maxResolutionX;
resolution.y = (int) newY;
}
if (resolution.y > CommonConfig.Screen.maxResolutionY) {
float newX = ((float) resolution.x) * ((float) CommonConfig.Screen.maxResolutionY) / ((float) resolution.y);
resolution.x = (int) newX;
resolution.y = CommonConfig.Screen.maxResolutionY;
}
}
public void createBrowser(ScreenBlockEntity be, boolean doAnim) {
if (WebDisplays.PROXY instanceof ClientProxy) {
browser = WDBrowser.createBrowser(WebDisplays.applyBlacklist(url != null ? url : "https://www.google.com"), false);
// set screen
if (browser instanceof MCEFBrowser mcefBrowser) {
if (rotation.isVertical)
mcefBrowser.resize(resolution.y, resolution.x);
else
mcefBrowser.resize(resolution.x, resolution.y);
mcefBrowser.setCursorChangeListener((type) -> mouseType = type);
}
// setup screen as in world
if (browser instanceof WDBrowser wdBrowser) {
InWorldQueries.attach(be, side, wdBrowser);
}
doTurnOnAnim = doAnim;
turnOnTime = System.currentTimeMillis();
}
}
}

View File

@ -3,7 +3,6 @@
*/ */
package net.montoyo.wd.entity; package net.montoyo.wd.entity;
/* /*
import dan200.computercraft.api.lua.ILuaContext; import dan200.computercraft.api.lua.ILuaContext;
import dan200.computercraft.api.lua.LuaException; import dan200.computercraft.api.lua.LuaException;
@ -20,17 +19,18 @@ import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
@Optional.Interface(iface = "dan200.computercraft.api.peripheral.IPeripheral", modid = "computercraft") @Optional.Interface(iface = "dan200.computercraft.api.peripheral.IPeripheral", modid = "computercraft")
public class CCInterfaceBlockEntity extends AbstractInterfaceBlockEntity implements IPeripheral { public class TileEntityCCInterface extends TileEntityInterfaceBase implements IPeripheral {
private static final String[] METHOD_NAMES; private static final String[] METHOD_NAMES;
private static final Method[] METHODS; private static final Method[] METHODS;
static { static {
ArrayList<String> names = new ArrayList<>(); ArrayList<String> names = new ArrayList<>();
ArrayList<Method> methods = new ArrayList<>(); ArrayList<Method> methods = new ArrayList<>();
Method[] src = AbstractInterfaceBlockEntity.class.getMethods(); Method[] src = TileEntityInterfaceBase.class.getMethods();
for(Method m: src) { for(Method m: src) {
if(m.getAnnotation(AbstractInterfaceBlockEntity.ComputerFunc.class) != null) { if(m.getAnnotation(TileEntityInterfaceBase.ComputerFunc.class) != null) {
if(m.getParameterCount() != 1 || m.getParameterTypes()[0] != IComputerArgs.class) if(m.getParameterCount() != 1 || m.getParameterTypes()[0] != IComputerArgs.class)
throw new RuntimeException("Found @ComputerFunc method with invalid arguments"); throw new RuntimeException("Found @ComputerFunc method with invalid arguments");
@ -79,4 +79,5 @@ public class CCInterfaceBlockEntity extends AbstractInterfaceBlockEntity impleme
public boolean equals(@Nullable IPeripheral periph) { public boolean equals(@Nullable IPeripheral periph) {
return periph == this; return periph == this;
} }
}*/ }*/

View File

@ -13,11 +13,7 @@ import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.core.IComputerArgs; import net.montoyo.wd.core.IComputerArgs;
import net.montoyo.wd.core.IUpgrade; import net.montoyo.wd.core.IUpgrade;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.utilities.math.Vector2i; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.data.Rotation;
import net.montoyo.wd.utilities.serialization.NameUUIDPair;
import net.montoyo.wd.utilities.serialization.TypeData;
import net.montoyo.wd.utilities.serialization.Util;
import java.io.IOException; import java.io.IOException;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
@ -27,8 +23,9 @@ import java.lang.annotation.Target;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Map; import java.util.Map;
public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlockEntity { public abstract class TileEntityInterfaceBase extends TileEntityPeripheralBase {
public AbstractInterfaceBlockEntity(BlockEntityType<?> arg, BlockPos arg2, BlockState arg3) {
public TileEntityInterfaceBase(BlockEntityType<?> arg, BlockPos arg2, BlockState arg3) {
super(arg, arg2, arg3); super(arg, arg2, arg3);
} }
@ -111,7 +108,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
throw new IllegalArgumentException("invalid right name"); throw new IllegalArgumentException("invalid right name");
} }
ScreenBlockEntity tes = getConnectedScreenEx(); TileEntityScreen tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
else else
@ -122,7 +119,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
public Object[] hasUpgrade(IComputerArgs args) { public Object[] hasUpgrade(IComputerArgs args) {
String name = args.checkString(0); String name = args.checkString(0);
ScreenBlockEntity tes = getConnectedScreenEx(); TileEntityScreen tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
else else
@ -131,7 +128,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
@ComputerFunc @ComputerFunc
public Object[] getSize(IComputerArgs args) { public Object[] getSize(IComputerArgs args) {
ScreenBlockEntity tes = getConnectedScreenEx(); TileEntityScreen tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
@ -143,7 +140,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
@ComputerFunc @ComputerFunc
public Object[] getResolution(IComputerArgs args) { public Object[] getResolution(IComputerArgs args) {
ScreenBlockEntity tes = getConnectedScreenEx(); TileEntityScreen tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
@ -155,7 +152,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
@ComputerFunc @ComputerFunc
public Object[] getRotation(IComputerArgs args) { public Object[] getRotation(IComputerArgs args) {
ScreenBlockEntity tes = getConnectedScreenEx(); TileEntityScreen tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
@ -165,7 +162,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
@ComputerFunc @ComputerFunc
public Object[] getURL(IComputerArgs args) { public Object[] getURL(IComputerArgs args) {
ScreenBlockEntity tes = getConnectedScreenEx(); TileEntityScreen tes = getConnectedScreenEx();
if(owner == null || tes == null) if(owner == null || tes == null)
return null; return null;
@ -209,12 +206,12 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
// throw new IllegalArgumentException("bad action name"); // throw new IllegalArgumentException("bad action name");
// } // }
ScreenBlockEntity scr = getConnectedScreenEx(); TileEntityScreen scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
else { else {
ScreenData scrscr = scr.getScreen(screenSide); TileEntityScreen.Screen scrscr = scr.getScreen(screenSide);
if((scrscr.rightsFor(owner.uuid) & ScreenRights.INTERACT) == 0) if((scrscr.rightsFor(owner.uuid) & ScreenRights.INTERACT) == 0)
return err("restrictions"); return err("restrictions");
@ -248,7 +245,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
} }
private Object[] realType(String what) { private Object[] realType(String what) {
ScreenBlockEntity scr = getConnectedScreenEx(); TileEntityScreen scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -329,7 +326,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
@ComputerFunc @ComputerFunc
public Object[] setURL(IComputerArgs args) { public Object[] setURL(IComputerArgs args) {
String url = args.checkString(0); String url = args.checkString(0);
ScreenBlockEntity scr = getConnectedScreenEx(); TileEntityScreen scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -349,7 +346,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
public Object[] setResolution(IComputerArgs args) { public Object[] setResolution(IComputerArgs args) {
int rx = args.checkInteger(0); int rx = args.checkInteger(0);
int ry = args.checkInteger(1); int ry = args.checkInteger(1);
ScreenBlockEntity scr = getConnectedScreenEx(); TileEntityScreen scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -372,7 +369,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
rot /= 90; rot /= 90;
rot &= 3; rot &= 3;
ScreenBlockEntity scr = getConnectedScreenEx(); TileEntityScreen scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -387,7 +384,7 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
@ComputerFunc @ComputerFunc
public Object[] runJS(IComputerArgs args) { public Object[] runJS(IComputerArgs args) {
String code = args.checkString(0); String code = args.checkString(0);
ScreenBlockEntity scr = getConnectedScreenEx(); TileEntityScreen scr = getConnectedScreenEx();
if(owner == null || scr == null) if(owner == null || scr == null)
return err("notlinked"); return err("notlinked");
@ -409,4 +406,5 @@ public abstract class AbstractInterfaceBlockEntity extends AbstractPeripheralBlo
return null; return null;
} }
} }

View File

@ -15,14 +15,15 @@ import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.data.KeyboardData; import net.montoyo.wd.data.KeyboardData;
import net.montoyo.wd.registry.TileRegistry; import net.montoyo.wd.init.TileInit;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
public class TileEntityKeyboard extends TileEntityPeripheralBase {
public class KeyboardBlockEntity extends AbstractPeripheralBlockEntity {
private static final String RANDOM_CHARS = "AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn0123456789"; //Yes I have an AZERTY keyboard, u care? private static final String RANDOM_CHARS = "AZERTYUIOPQSDFGHJKLMWXCVBNazertyuiopqsdfghjklmwxcvbn0123456789"; //Yes I have an AZERTY keyboard, u care?
public KeyboardBlockEntity(BlockPos arg2, BlockState arg3) { public TileEntityKeyboard(BlockPos arg2, BlockState arg3) {
super(TileRegistry.KEYBOARD.get(), arg2, arg3); super(TileInit.KEYBOARD.get(), arg2, arg3);
} }
@Override @Override
@ -35,13 +36,13 @@ public class KeyboardBlockEntity extends AbstractPeripheralBlockEntity {
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ScreenBlockEntity tes = getConnectedScreen(); TileEntityScreen tes = getConnectedScreen();
if(tes == null) { if(tes == null) {
Util.toast(player, "notLinked"); Util.toast(player, "notLinked");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ScreenData scr = tes.getScreen(screenSide); TileEntityScreen.Screen scr = tes.getScreen(screenSide);
if((scr.rightsFor(player) & ScreenRights.INTERACT) == 0) { if((scr.rightsFor(player) & ScreenRights.INTERACT) == 0) {
Util.toast(player, "restrictions"); Util.toast(player, "restrictions");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@ -55,10 +56,10 @@ public class KeyboardBlockEntity extends AbstractPeripheralBlockEntity {
if(!isScreenChunkLoaded()) if(!isScreenChunkLoaded())
return; return;
ScreenBlockEntity tes = getConnectedScreen(); TileEntityScreen tes = getConnectedScreen();
if(tes != null) { if(tes != null) {
ScreenData scr = tes.getScreen(screenSide); TileEntityScreen.Screen scr = tes.getScreen(screenSide);
boolean ok; boolean ok;
if(ent instanceof Player) if(ent instanceof Player)
@ -71,9 +72,10 @@ public class KeyboardBlockEntity extends AbstractPeripheralBlockEntity {
tes.type(screenSide, "t" + rnd, getBlockPos()); tes.type(screenSide, "t" + rnd, getBlockPos());
Player owner = level.getPlayerByUUID(scr.owner.uuid); Player owner = level.getPlayerByUUID(scr.owner.uuid);
if(owner instanceof ServerPlayer && ent instanceof Ocelot) if(owner != null && owner instanceof ServerPlayer && ent instanceof Ocelot)
WebDisplays.INSTANCE.criterionKeyboardCat.trigger(((ServerPlayer) owner).getAdvancements()); WebDisplays.INSTANCE.criterionKeyboardCat.trigger(((ServerPlayer) owner).getAdvancements());
} }
} }
} }
} }

View File

@ -13,7 +13,8 @@ import net.minecraftforge.fml.common.Optional;
import net.montoyo.wd.core.OCArguments; import net.montoyo.wd.core.OCArguments;
@Optional.Interface(iface = "li.cil.oc.api.network.SimpleComponent", modid = "opencomputers") @Optional.Interface(iface = "li.cil.oc.api.network.SimpleComponent", modid = "opencomputers")
public class OCInterfaceBlockEntity extends AbstractInterfaceBlockEntity implements SimpleComponent { public class TileEntityOCInterface extends TileEntityInterfaceBase implements SimpleComponent {
@Override @Override
public String getComponentName() { public String getComponentName() {
return "webdisplays"; return "webdisplays";
@ -132,4 +133,5 @@ public class OCInterfaceBlockEntity extends AbstractInterfaceBlockEntity impleme
public Object[] unlink(Context ctx, Arguments args) { public Object[] unlink(Context ctx, Arguments args) {
return unlink(new OCArguments(args)); return unlink(new OCArguments(args));
} }
}*/ }*/

View File

@ -16,19 +16,20 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunk;
import net.montoyo.wd.core.IPeripheral; import net.montoyo.wd.core.IPeripheral;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.Objects; import java.util.Objects;
public abstract class AbstractPeripheralBlockEntity extends BlockEntity implements IPeripheral { public abstract class TileEntityPeripheralBase extends BlockEntity implements IPeripheral {
protected Vector3i screenPos; protected Vector3i screenPos;
protected BlockSide screenSide; protected BlockSide screenSide;
public AbstractPeripheralBlockEntity(BlockEntityType<?> arg, BlockPos arg2, BlockState arg3) { public TileEntityPeripheralBase(BlockEntityType<?> arg, BlockPos arg2, BlockState arg3) {
super(arg, arg2, arg3); super(arg, arg2, arg3);
} }
@ -37,7 +38,7 @@ public abstract class AbstractPeripheralBlockEntity extends BlockEntity implemen
public void load(CompoundTag tag) { public void load(CompoundTag tag) {
super.load(tag); super.load(tag);
if (tag.contains("WDScreen", 10)) { if(tag.contains("WDScreen", 10)) {
CompoundTag scr = tag.getCompound("WDScreen"); CompoundTag scr = tag.getCompound("WDScreen");
screenPos = new Vector3i(scr.getInt("X"), scr.getInt("Y"), scr.getInt("Z")); screenPos = new Vector3i(scr.getInt("X"), scr.getInt("Y"), scr.getInt("Z"));
screenSide = BlockSide.values()[scr.getByte("Side")]; screenSide = BlockSide.values()[scr.getByte("Side")];
@ -51,7 +52,7 @@ public abstract class AbstractPeripheralBlockEntity extends BlockEntity implemen
protected void saveAdditional(CompoundTag tag) { protected void saveAdditional(CompoundTag tag) {
super.saveAdditional(tag); super.saveAdditional(tag);
if (screenPos != null && screenSide != null) { if(screenPos != null && screenSide != null) {
CompoundTag scr = new CompoundTag(); CompoundTag scr = new CompoundTag();
scr.putInt("X", screenPos.x); scr.putInt("X", screenPos.x);
scr.putInt("Y", screenPos.y); scr.putInt("Y", screenPos.y);
@ -78,12 +79,12 @@ public abstract class AbstractPeripheralBlockEntity extends BlockEntity implemen
@Override @Override
public boolean connect(Level world_, BlockPos blockPos, BlockState blockState, Vector3i pos, BlockSide side) { public boolean connect(Level world_, BlockPos blockPos, BlockState blockState, Vector3i pos, BlockSide side) {
BlockEntity te = world_.getBlockEntity(pos.toBlock()); BlockEntity te = world_.getBlockEntity(pos.toBlock());
if (!(te instanceof ScreenBlockEntity)) { if(te == null || !(te instanceof TileEntityScreen)) {
Log.error("TileEntityPeripheralBase.connect(): Tile entity at %s is not a screen!", pos.toString()); Log.error("TileEntityPeripheralBase.connect(): Tile entity at %s is not a screen!", pos.toString());
return false; return false;
} }
if (((ScreenBlockEntity) te).getScreen(side) == null) { if(((TileEntityScreen) te).getScreen(side) == null) {
Log.error("TileEntityPeripheralBase.connect(): There is no screen at %s on side %s!", pos.toString(), side.toString()); Log.error("TileEntityPeripheralBase.connect(): There is no screen at %s on side %s!", pos.toString(), side.toString());
return false; return false;
} }
@ -107,31 +108,31 @@ public abstract class AbstractPeripheralBlockEntity extends BlockEntity implemen
} }
@Nullable @Nullable
public ScreenBlockEntity getConnectedScreen() { public TileEntityScreen getConnectedScreen() {
if (screenPos == null || screenSide == null) if(screenPos == null || screenSide == null)
return null; return null;
BlockEntity te = level.getBlockEntity(screenPos.toBlock()); BlockEntity te = level.getBlockEntity(screenPos.toBlock());
if (!(te instanceof ScreenBlockEntity) || ((ScreenBlockEntity) te).getScreen(screenSide) == null) { if(te == null || !(te instanceof TileEntityScreen) || ((TileEntityScreen) te).getScreen(screenSide) == null) {
screenPos = null; screenPos = null;
screenSide = null; screenSide = null;
setChanged(); setChanged();
return null; return null;
} }
return (ScreenBlockEntity) te; return (TileEntityScreen) te;
} }
@Nullable @Nullable
public ScreenBlockEntity getConnectedScreenEx() { public TileEntityScreen getConnectedScreenEx() {
if (screenPos == null || screenSide == null) if(screenPos == null || screenSide == null)
return null; return null;
BlockEntity te = level.getBlockEntity(screenPos.toBlock()); BlockEntity te = level.getBlockEntity(screenPos.toBlock());
if (!(te instanceof ScreenBlockEntity) || ((ScreenBlockEntity) te).getScreen(screenSide) == null) if(te == null || !(te instanceof TileEntityScreen) || ((TileEntityScreen) te).getScreen(screenSide) == null)
return null; return null;
return (ScreenBlockEntity) te; return (TileEntityScreen) te;
} }
@Nullable @Nullable

View File

@ -12,31 +12,31 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.data.SetURLData; import net.montoyo.wd.data.SetURLData;
import net.montoyo.wd.registry.TileRegistry; import net.montoyo.wd.init.TileInit;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
public class RemoteControlBlockEntity extends AbstractPeripheralBlockEntity { public class TileEntityRCtrl extends TileEntityPeripheralBase {
public RemoteControlBlockEntity(BlockPos arg2, BlockState arg3) { public TileEntityRCtrl(BlockPos arg2, BlockState arg3) {
super(TileRegistry.REMOTE_CONTROLLER.get(), arg2, arg3); super(TileInit.REMOTE_CONTROLLER.get(), arg2, arg3);
} }
@Override @Override
public InteractionResult onRightClick(Player player, InteractionHand hand) { public InteractionResult onRightClick(Player player, InteractionHand hand) {
if (level.isClientSide) if(level.isClientSide)
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
if (!isScreenChunkLoaded()) { if(!isScreenChunkLoaded()) {
Util.toast(player, "chunkUnloaded"); Util.toast(player, "chunkUnloaded");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ScreenBlockEntity tes = getConnectedScreen(); TileEntityScreen tes = getConnectedScreen();
if (tes == null) { if(tes == null) {
Util.toast(player, "notLinked"); Util.toast(player, "notLinked");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ScreenData scr = tes.getScreen(screenSide); TileEntityScreen.Screen scr = tes.getScreen(screenSide);
if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) { if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) {
Util.toast(player, "restrictions"); Util.toast(player, "restrictions");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@ -45,4 +45,5 @@ public class RemoteControlBlockEntity extends AbstractPeripheralBlockEntity {
(new SetURLData(screenPos, screenSide, scr.url, getBlockPos())).sendTo((ServerPlayer) player); (new SetURLData(screenPos, screenSide, scr.url, getBlockPos())).sendTo((ServerPlayer) player);
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
} }

View File

@ -14,18 +14,19 @@ import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.data.RedstoneCtrlData; import net.montoyo.wd.data.RedstoneCtrlData;
import net.montoyo.wd.registry.TileRegistry; import net.montoyo.wd.init.TileInit;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import java.io.IOException; import java.io.IOException;
public class RedstoneControlBlockEntity extends AbstractPeripheralBlockEntity { public class TileEntityRedCtrl extends TileEntityPeripheralBase {
private String risingEdgeURL = ""; private String risingEdgeURL = "";
private String fallingEdgeURL = ""; private String fallingEdgeURL = "";
private boolean state = false; private boolean state = false;
public RedstoneControlBlockEntity(BlockPos arg2, BlockState arg3) { public TileEntityRedCtrl(BlockPos arg2, BlockState arg3) {
super(TileRegistry.REDSTONE_CONTROLLER.get(), arg2, arg3); super(TileInit.REDSTONE_CONTROLLER.get(), arg2, arg3);
} }
@Override @Override
@ -47,21 +48,21 @@ public class RedstoneControlBlockEntity extends AbstractPeripheralBlockEntity {
@Override @Override
public InteractionResult onRightClick(Player player, InteractionHand hand) { public InteractionResult onRightClick(Player player, InteractionHand hand) {
if (level.isClientSide) if(level.isClientSide)
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
if (!isScreenChunkLoaded()) { if(!isScreenChunkLoaded()) {
Util.toast(player, "chunkUnloaded"); Util.toast(player, "chunkUnloaded");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ScreenBlockEntity tes = getConnectedScreen(); TileEntityScreen tes = getConnectedScreen();
if (tes == null) { if(tes == null) {
Util.toast(player, "notLinked"); Util.toast(player, "notLinked");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ScreenData scr = tes.getScreen(screenSide); TileEntityScreen.Screen scr = tes.getScreen(screenSide);
if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) { if((scr.rightsFor(player) & ScreenRights.CHANGE_URL) == 0) {
Util.toast(player, "restrictions"); Util.toast(player, "restrictions");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@ -75,10 +76,10 @@ public class RedstoneControlBlockEntity extends AbstractPeripheralBlockEntity {
public void onNeighborChange(Block neighborType, BlockPos neighborPos) { public void onNeighborChange(Block neighborType, BlockPos neighborPos) {
boolean hasPower = (level.hasNeighborSignal(getBlockPos()) || level.hasNeighborSignal(getBlockPos().above())); //Same as dispenser boolean hasPower = (level.hasNeighborSignal(getBlockPos()) || level.hasNeighborSignal(getBlockPos().above())); //Same as dispenser
if (hasPower != state) { if(hasPower != state) {
state = hasPower; state = hasPower;
if (state) //Rising edge if(state) //Rising edge
changeURL(risingEdgeURL); changeURL(risingEdgeURL);
else //Falling edge else //Falling edge
changeURL(fallingEdgeURL); changeURL(fallingEdgeURL);
@ -92,11 +93,11 @@ public class RedstoneControlBlockEntity extends AbstractPeripheralBlockEntity {
} }
private void changeURL(String url) { private void changeURL(String url) {
if (level.isClientSide || url.isEmpty()) if(level.isClientSide || url.isEmpty())
return; return;
if (isScreenChunkLoaded()) { if(isScreenChunkLoaded()) {
ScreenBlockEntity tes = getConnectedScreen(); TileEntityScreen tes = getConnectedScreen();
if (tes != null) if (tes != null)
try { try {

File diff suppressed because it is too large Load Diff

View File

@ -12,15 +12,16 @@ import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.data.ServerData; import net.montoyo.wd.data.ServerData;
import net.montoyo.wd.registry.TileRegistry; import net.montoyo.wd.init.TileInit;
import net.montoyo.wd.utilities.serialization.NameUUIDPair; import net.montoyo.wd.utilities.NameUUIDPair;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
public class TileEntityServer extends BlockEntity {
public class ServerBlockEntity extends BlockEntity {
private NameUUIDPair owner; private NameUUIDPair owner;
public ServerBlockEntity(BlockPos arg2, BlockState arg3) { public TileEntityServer(BlockPos arg2, BlockState arg3) {
super(TileRegistry.SERVER.get(), arg2, arg3); super(TileInit.SERVER.get(), arg2, arg3);
} }
@Override @Override
@ -41,12 +42,13 @@ public class ServerBlockEntity extends BlockEntity {
} }
public void onPlayerRightClick(Player ply) { public void onPlayerRightClick(Player ply) {
if (level.isClientSide) if(level.isClientSide)
return; return;
if (WebDisplays.INSTANCE.miniservPort == 0) if( WebDisplays.INSTANCE.miniservPort == 0)
Util.toast(ply, "noMiniserv"); Util.toast(ply, "noMiniserv");
else if (owner != null && ply instanceof ServerPlayer) else if(owner != null && ply instanceof ServerPlayer)
(new ServerData(getBlockPos(), owner)).sendTo((ServerPlayer) ply); (new ServerData(getBlockPos(), owner)).sendTo((ServerPlayer) ply);
} }
} }

View File

@ -0,0 +1,32 @@
package net.montoyo.wd.init;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import net.montoyo.wd.block.BlockKeyboardLeft;
import net.montoyo.wd.block.BlockKeyboardRight;
import net.montoyo.wd.block.BlockPeripheral;
import net.montoyo.wd.block.BlockScreen;
import net.montoyo.wd.core.DefaultPeripheral;
public class BlockInit {
public static void init(IEventBus bus) {
BLOCKS.register(bus);
}
public static DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, "webdisplays");
public static final RegistryObject<BlockScreen> blockScreen = BLOCKS.register("screen", () -> new BlockScreen(BlockBehaviour.Properties.copy(Blocks.STONE)));
public static final RegistryObject<BlockKeyboardLeft> blockKeyBoard = BlockInit.BLOCKS.register("kb_left", BlockKeyboardLeft::new);
public static final RegistryObject<BlockKeyboardRight> blockKbRight = BLOCKS.register("kb_right", BlockKeyboardRight::new);
public static final RegistryObject<BlockPeripheral> blockRedControl = BlockInit.BLOCKS.register("redctrl", () -> new BlockPeripheral(DefaultPeripheral.REDSTONE_CONTROLLER));
public static final RegistryObject<BlockPeripheral> blockRControl = BlockInit.BLOCKS.register("rctrl", () -> new BlockPeripheral(DefaultPeripheral.REMOTE_CONTROLLER));
public static final RegistryObject<BlockPeripheral> blockServer = BlockInit.BLOCKS.register("server", () -> new BlockPeripheral(DefaultPeripheral.SERVER));
}

View File

@ -1,4 +1,4 @@
package net.montoyo.wd.registry; package net.montoyo.wd.init;
import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
@ -6,6 +6,7 @@ import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject; import net.minecraftforge.registries.RegistryObject;
import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.block.item.KeyboardItem; import net.montoyo.wd.block.item.KeyboardItem;
import net.montoyo.wd.core.CraftComponent; import net.montoyo.wd.core.CraftComponent;
import net.montoyo.wd.core.DefaultUpgrade; import net.montoyo.wd.core.DefaultUpgrade;
@ -14,7 +15,7 @@ import net.montoyo.wd.item.*;
import java.util.Locale; import java.util.Locale;
@SuppressWarnings({"unchecked", "unused"}) @SuppressWarnings({"unchecked", "unused"})
public class ItemRegistry { public class ItemInit{
public static void init(IEventBus bus) { public static void init(IEventBus bus) {
ITEMS.register(bus); ITEMS.register(bus);
} }
@ -30,7 +31,7 @@ public class ItemRegistry {
public static final RegistryObject<Item> MINEPAD = ITEMS.register("minepad", () -> new ItemMinePad2(new Item.Properties())); public static final RegistryObject<Item> MINEPAD = ITEMS.register("minepad", () -> new ItemMinePad2(new Item.Properties()));
public static final RegistryObject<Item> LASER_POINTER = ITEMS.register("laserpointer", () -> new ItemLaserPointer(new Item.Properties())); public static final RegistryObject<Item> LASER_POINTER = ITEMS.register("laserpointer", () -> new ItemLaserPointer(new Item.Properties()));
static { static {
DefaultUpgrade[] defaultUpgrades = DefaultUpgrade.values(); DefaultUpgrade[] defaultUpgrades = DefaultUpgrade.values();
for (int i = 0; i < defaultUpgrades.length; i++) { for (int i = 0; i < defaultUpgrades.length; i++) {
DefaultUpgrade upgrade = defaultUpgrades[i]; DefaultUpgrade upgrade = defaultUpgrades[i];
@ -44,12 +45,12 @@ public class ItemRegistry {
} }
} }
public static final RegistryObject<Item> SCREEN = ITEMS.register("screen", () -> new BlockItem(BlockRegistry.SCREEN_BLOCk.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/)); public static final RegistryObject<Item> SCREEN = ITEMS.register("screen", () -> new BlockItem(BlockInit.blockScreen.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/));
public static final RegistryObject<Item> KEYBOARD = ITEMS.register("keyboard", () -> new KeyboardItem(BlockRegistry.KEYBOARD_BLOCK.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/)); public static final RegistryObject<Item> KEYBOARD = ITEMS.register("keyboard", () -> new KeyboardItem(BlockInit.blockKeyBoard.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/));
public static final RegistryObject<Item> REDSTONE_CONTROLLER = ITEMS.register("redctrl", () -> new BlockItem(BlockRegistry.REDSTONE_CONTROL_BLOCK.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/)); public static final RegistryObject<Item> REDSTONE_CONTROLLER = ITEMS.register("redctrl", () -> new BlockItem(BlockInit.blockRedControl.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/));
public static final RegistryObject<Item> REMOTE_CONTROLLER = ITEMS.register("rctrl", () -> new BlockItem(BlockRegistry.REMOTE_CONTROLLER_BLOCK.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/)); public static final RegistryObject<Item> REMOTE_CONTROLLER = ITEMS.register("rctrl", () -> new BlockItem(BlockInit.blockRControl.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/));
public static final RegistryObject<Item> SERVER = ITEMS.register("server", () -> new BlockItem(BlockRegistry.SERVER_BLOCK.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/)); public static final RegistryObject<Item> SERVER = ITEMS.register("server", () -> new BlockItem(BlockInit.blockServer.get(), new Item.Properties()/*.tab(WebDisplays.CREATIVE_TAB)*/));
public static RegistryObject<Item> getComputerCraftItem(int index) { public static RegistryObject<Item> getComputerCraftItem(int index) {
return COMP_CRAFT_ITEMS[index]; return COMP_CRAFT_ITEMS[index];

View File

@ -2,7 +2,7 @@
* Copyright (C) 2018 BARBOTIN Nicolas * Copyright (C) 2018 BARBOTIN Nicolas
*/ */
package net.montoyo.wd.registry; package net.montoyo.wd.init;
import net.minecraft.core.registries.Registries; import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
@ -11,37 +11,38 @@ import net.minecraft.world.item.ItemStack;
import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.RegistryObject; import net.minecraftforge.registries.RegistryObject;
import net.montoyo.wd.init.ItemInit;
public class WDTabs { public class TabInit {
public static final DeferredRegister<CreativeModeTab> TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, "webdisplays"); public static final DeferredRegister<CreativeModeTab> TABS = DeferredRegister.create(Registries.CREATIVE_MODE_TAB, "webdisplays");
public static final RegistryObject<CreativeModeTab> EXAMPLE_TAB = TABS.register("main", () -> CreativeModeTab.builder() public static final RegistryObject<CreativeModeTab> EXAMPLE_TAB = TABS.register("main", () -> CreativeModeTab.builder()
// Set name of tab to display // Set name of tab to display
.title(Component.translatable("itemGroup.webdisplays")) .title(Component.translatable("itemGroup.webdisplays"))
// Set icon of creative tab // Set icon of creative tab
.icon(() -> new ItemStack(ItemRegistry.SCREEN.get())) .icon(() -> new ItemStack(ItemInit.SCREEN.get()))
// Add default items to tab // Add default items to tab
.displayItems((params, output) -> { .displayItems((params, output) -> {
// core items // core items
output.accept(ItemRegistry.SCREEN.get()); output.accept(ItemInit.SCREEN.get());
output.accept(ItemRegistry.KEYBOARD.get()); output.accept(ItemInit.KEYBOARD.get());
output.accept(ItemRegistry.LINKER.get()); output.accept(ItemInit.LINKER.get());
// remote control // remote control
output.accept(ItemRegistry.REMOTE_CONTROLLER.get()); output.accept(ItemInit.REMOTE_CONTROLLER.get());
// redstone stuff // redstone stuff
output.accept(ItemRegistry.REDSTONE_CONTROLLER.get()); output.accept(ItemInit.REDSTONE_CONTROLLER.get());
// admin tools // admin tools
output.accept(ItemRegistry.OWNERSHIP_THEIF.get()); output.accept(ItemInit.OWNERSHIP_THEIF.get());
// tool items // tool items
output.accept(ItemRegistry.SERVER.get()); output.accept(ItemInit.SERVER.get());
output.accept(ItemRegistry.CONFIGURATOR.get()); output.accept(ItemInit.CONFIGURATOR.get());
output.accept(ItemRegistry.MINEPAD.get()); output.accept(ItemInit.MINEPAD.get());
output.accept(ItemRegistry.LASER_POINTER.get()); output.accept(ItemInit.LASER_POINTER.get());
// upgrades // upgrades
for (int i = 0; i < ItemRegistry.countUpgrades(); i++) output.accept(ItemRegistry.getUpgradeItem(i).get()); for (int i = 0; i < ItemInit.countUpgrades(); i++) output.accept(ItemInit.getUpgradeItem(i).get());
// cc // cc
for (int i = 0; i < ItemRegistry.countCompCraftItems(); i++) output.accept(ItemRegistry.getComputerCraftItem(i).get()); for (int i = 0; i < ItemInit.countCompCraftItems(); i++) output.accept(ItemInit.getComputerCraftItem(i).get());
}) })
.build() .build()
); );

View File

@ -0,0 +1,39 @@
package net.montoyo.wd.init;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import net.montoyo.wd.core.DefaultPeripheral;
import net.montoyo.wd.entity.*;
import java.util.Locale;
public class TileInit {
public static final DeferredRegister<BlockEntityType<?>> TILE_TYPES = DeferredRegister
.create(ForgeRegistries.BLOCK_ENTITY_TYPES, "webdisplays");
//Register tile entities
public static final RegistryObject<BlockEntityType<TileEntityScreen>> SCREEN_BLOCK_ENTITY = TILE_TYPES
.register("screen", () -> BlockEntityType.Builder
.of(TileEntityScreen::new, BlockInit.blockScreen.get()).build(null));
public static final RegistryObject<BlockEntityType<?>> KEYBOARD = TILE_TYPES.register("kb_left", () -> BlockEntityType.Builder
.of(TileEntityKeyboard::new, BlockInit.blockKeyBoard.get()).build(null));
public static final RegistryObject<BlockEntityType<?>> REMOTE_CONTROLLER = TILE_TYPES.register("rctrl",
() -> BlockEntityType.Builder.of(TileEntityRCtrl::new, BlockInit.blockRControl.get()).build(null)); //WITHOUT FACING (>= 3)
public static final RegistryObject<BlockEntityType<?>> REDSTONE_CONTROLLER = TILE_TYPES.register("redctrl",
() -> BlockEntityType.Builder.of(TileEntityRedCtrl::new, BlockInit.blockRedControl.get()).build(null));
public static final RegistryObject<BlockEntityType<?>> SERVER = TILE_TYPES.register("server" ,
() -> BlockEntityType.Builder.of(TileEntityServer::new, BlockInit.blockServer.get()).build(null));
public static void init(IEventBus bus) {
TILE_TYPES.register(bus);
}
}

View File

@ -10,6 +10,7 @@ import net.montoyo.wd.core.CraftComponent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class ItemCraftComponent extends ItemMulti implements WDItem { public class ItemCraftComponent extends ItemMulti implements WDItem {
public ItemCraftComponent(Properties properties) { public ItemCraftComponent(Properties properties) {
super(CraftComponent.class, properties super(CraftComponent.class, properties
// .tab(WebDisplays.CREATIVE_TAB) // .tab(WebDisplays.CREATIVE_TAB)

View File

@ -11,20 +11,20 @@ import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult;
import net.montoyo.wd.block.ScreenBlock; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.block.BlockScreen;
import net.montoyo.wd.client.ClientProxy; import net.montoyo.wd.client.ClientProxy;
import net.montoyo.wd.config.ClientConfig; import net.montoyo.wd.config.ClientConfig;
import net.montoyo.wd.controls.builtin.ClickControl; import net.montoyo.wd.controls.builtin.ClickControl;
import net.montoyo.wd.core.DefaultUpgrade; import net.montoyo.wd.core.DefaultUpgrade;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.init.BlockInit;
import net.montoyo.wd.net.WDNetworkRegistry; import net.montoyo.wd.net.WDNetworkRegistry;
import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl; import net.montoyo.wd.net.server_bound.C2SMessageScreenCtrl;
import net.montoyo.wd.registry.BlockRegistry; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.Multiblock; import net.montoyo.wd.utilities.Multiblock;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.Vector2i;
import net.montoyo.wd.utilities.math.Vector2i; import net.montoyo.wd.utilities.Vector3i;
import net.montoyo.wd.utilities.math.Vector3i;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -39,7 +39,7 @@ public class ItemLaserPointer extends Item implements WDItem {
} }
//Laser pointer //Laser pointer
private static ScreenBlockEntity pointedScreen; private static TileEntityScreen pointedScreen;
private static BlockSide pointedScreenSide; private static BlockSide pointedScreenSide;
private static long lastPointPacket; private static long lastPointPacket;
@ -53,16 +53,16 @@ public class ItemLaserPointer extends Item implements WDItem {
BlockPos bpos = result.getBlockPos(); BlockPos bpos = result.getBlockPos();
if (result.getType() == HitResult.Type.BLOCK && mc.level.getBlockState(bpos).getBlock() == BlockRegistry.SCREEN_BLOCk.get()) { if (result.getType() == HitResult.Type.BLOCK && mc.level.getBlockState(bpos).getBlock() == BlockInit.blockScreen.get()) {
Vector3i pos = new Vector3i(result.getBlockPos()); Vector3i pos = new Vector3i(result.getBlockPos());
BlockSide side = BlockSide.values()[result.getDirection().ordinal()]; BlockSide side = BlockSide.values()[result.getDirection().ordinal()];
Multiblock.findOrigin(mc.level, pos, side, null); Multiblock.findOrigin(mc.level, pos, side, null);
ScreenBlockEntity te = (ScreenBlockEntity) mc.level.getBlockEntity(pos.toBlock()); TileEntityScreen te = (TileEntityScreen) mc.level.getBlockEntity(pos.toBlock());
if (te != null && te.hasUpgrade(side, DefaultUpgrade.LASERMOUSE)) { //hasUpgrade returns false is there's no screen on side 'side' if (te != null && te.hasUpgrade(side, DefaultUpgrade.LASERMOUSE)) { //hasUpgrade returns false is there's no screen on side 'side'
//Since rights aren't synchronized, let the server check them for us... //Since rights aren't synchronized, let the server check them for us...
ScreenData scr = te.getScreen(side); TileEntityScreen.Screen scr = te.getScreen(side);
if (scr.browser != null) { if (scr.browser != null) {
float hitX = ((float) result.getLocation().x) - (float) pos.x; float hitX = ((float) result.getLocation().x) - (float) pos.x;
@ -70,7 +70,7 @@ public class ItemLaserPointer extends Item implements WDItem {
float hitZ = ((float) result.getLocation().z) - (float) pos.z; float hitZ = ((float) result.getLocation().z) - (float) pos.z;
Vector2i tmp = new Vector2i(); Vector2i tmp = new Vector2i();
if (ScreenBlock.hit2pixels(side, bpos, new Vector3i(result.getBlockPos()), scr, hitX, hitY, hitZ, tmp)) { if (BlockScreen.hit2pixels(side, bpos, new Vector3i(result.getBlockPos()), scr, hitX, hitY, hitZ, tmp)) {
laserClick(te, side, scr, tmp); laserClick(te, side, scr, tmp);
} }
} }
@ -82,7 +82,7 @@ public class ItemLaserPointer extends Item implements WDItem {
deselectScreen(); deselectScreen();
} }
private static void laserClick(ScreenBlockEntity tes, BlockSide side, ScreenData scr, Vector2i hit) { private static void laserClick(TileEntityScreen tes, BlockSide side, TileEntityScreen.Screen scr, Vector2i hit) {
tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1); tes.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
if (pointedScreen == tes && pointedScreenSide == side) { if (pointedScreen == tes && pointedScreenSide == side) {
long t = System.currentTimeMillis(); long t = System.currentTimeMillis();
@ -106,7 +106,7 @@ public class ItemLaserPointer extends Item implements WDItem {
} }
public static void press(boolean press, int button) { public static void press(boolean press, int button) {
if (button <= 1 && ClientConfig.Input.switchButtons) if (button <= 1 && ClientConfig.switchButtons)
button = 1 - button; button = 1 - button;
if (button == 0) left = press; if (button == 0) left = press;
@ -120,23 +120,32 @@ public class ItemLaserPointer extends Item implements WDItem {
BlockSide side = BlockSide.values()[result.getDirection().ordinal()]; BlockSide side = BlockSide.values()[result.getDirection().ordinal()];
Multiblock.findOrigin(mc.level, pos, side, null); Multiblock.findOrigin(mc.level, pos, side, null);
float hitX = ((float) result.getLocation().x) - (float) pos.x;
float hitY = ((float) result.getLocation().y) - (float) pos.y;
float hitZ = ((float) result.getLocation().z) - (float) pos.z;
Vector2i tmp = new Vector2i();
BlockEntity be = mc.level.getBlockEntity(pos.toBlock()); BlockEntity be = mc.level.getBlockEntity(pos.toBlock());
if (!(be instanceof ScreenBlockEntity)) return; if (!(be instanceof TileEntityScreen)) return;
//noinspection PatternVariableCanBeUsed //noinspection PatternVariableCanBeUsed
ScreenBlockEntity te = (ScreenBlockEntity) be; TileEntityScreen te = (TileEntityScreen) be;
if (te.hasUpgrade(side, DefaultUpgrade.LASERMOUSE)) { //hasUpgrade returns false is there's no screen on side 'side' if (te.hasUpgrade(side, DefaultUpgrade.LASERMOUSE)) { //hasUpgrade returns false is there's no screen on side 'side'
int finalButton = button; //Since rights aren't synchronized, let the server check them for us...
te.interact(result, (hit) -> { TileEntityScreen.Screen scr = te.getScreen(side);
te.handleMouseEvent(side, ClickControl.ControlType.MOVE, hit, -1);
te.handleMouseEvent(side, press ? ClickControl.ControlType.DOWN : ClickControl.ControlType.UP, hit, finalButton);
if (press) if (scr.browser != null) {
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserDown(te, side, hit, finalButton)); if (BlockScreen.hit2pixels(side, result.getBlockPos(), new Vector3i(result.getBlockPos()), scr, hitX, hitY, hitZ, tmp)) {
else te.handleMouseEvent(side, ClickControl.ControlType.MOVE, tmp, -1);
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserUp(te, side, finalButton)); te.handleMouseEvent(side, press ? ClickControl.ControlType.DOWN : ClickControl.ControlType.UP, tmp, button);
});
if (press)
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserDown(te, side, tmp, button));
else
WDNetworkRegistry.INSTANCE.sendToServer(C2SMessageScreenCtrl.laserUp(te, side, button));
}
}
} }
} }

View File

@ -14,46 +14,46 @@ import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.block.ScreenBlock; import net.montoyo.wd.block.BlockScreen;
import net.montoyo.wd.core.IPeripheral; import net.montoyo.wd.core.IPeripheral;
import net.montoyo.wd.core.ScreenRights; import net.montoyo.wd.core.ScreenRights;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Multiblock; import net.montoyo.wd.utilities.Multiblock;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class ItemLinker extends Item implements WDItem { public class ItemLinker extends Item implements WDItem {
public ItemLinker(Properties properties) { public ItemLinker(Properties properties) {
super(properties super(properties
.stacksTo(1) .stacksTo(1)
// .tab(WebDisplays.CREATIVE_TAB) // .tab(WebDisplays.CREATIVE_TAB)
); );
} }
@Override @Override
public InteractionResult useOn(UseOnContext context) { public InteractionResult useOn(UseOnContext context) {
if (context.getLevel().isClientSide()) if(context.getLevel().isClientSide())
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
ItemStack stack = context.getPlayer().getItemInHand(context.getHand()); ItemStack stack = context.getPlayer().getItemInHand(context.getHand());
CompoundTag tag = stack.getTag(); CompoundTag tag = stack.getTag();
if (tag != null) { if(tag != null) {
if (tag.contains("ScreenX") && tag.contains("ScreenY") && tag.contains("ScreenZ") && tag.contains("ScreenSide")) { if(tag.contains("ScreenX") && tag.contains("ScreenY") && tag.contains("ScreenZ") && tag.contains("ScreenSide")) {
BlockState state = context.getLevel().getBlockState(context.getClickedPos()); BlockState state = context.getLevel().getBlockState(context.getClickedPos());
IPeripheral target; IPeripheral target;
if (state.getBlock() instanceof IPeripheral) if(state.getBlock() instanceof IPeripheral)
target = (IPeripheral) state.getBlock(); target = (IPeripheral) state.getBlock();
else { else {
BlockEntity te = context.getLevel().getBlockEntity(context.getClickedPos()); BlockEntity te = context.getLevel().getBlockEntity(context.getClickedPos());
if (te == null || !(te instanceof IPeripheral)) { if(te == null || !(te instanceof IPeripheral)) {
if (context.getPlayer().isShiftKeyDown()) { if(context.getPlayer().isShiftKeyDown()) {
Util.toast(context.getPlayer(), ChatFormatting.GOLD, "linkAbort"); Util.toast(context.getPlayer(), ChatFormatting.GOLD, "linkAbort");
stack.setTag(null); stack.setTag(null);
} else } else
@ -68,10 +68,10 @@ public class ItemLinker extends Item implements WDItem {
Vector3i tePos = new Vector3i(tag.getInt("ScreenX"), tag.getInt("ScreenY"), tag.getInt("ScreenZ")); Vector3i tePos = new Vector3i(tag.getInt("ScreenX"), tag.getInt("ScreenY"), tag.getInt("ScreenZ"));
BlockSide scrSide = BlockSide.values()[tag.getByte("ScreenSide")]; BlockSide scrSide = BlockSide.values()[tag.getByte("ScreenSide")];
if (target.connect(context.getLevel(), context.getClickedPos(), state, tePos, scrSide)) { if(target.connect(context.getLevel(), context.getClickedPos(), state, tePos, scrSide)) {
Util.toast(context.getPlayer(), ChatFormatting.AQUA, "linked"); Util.toast(context.getPlayer(), ChatFormatting.AQUA, "linked");
if (context.getPlayer() instanceof ServerPlayer) if(context.getPlayer() instanceof ServerPlayer)
WebDisplays.INSTANCE.criterionLinkPeripheral.trigger(((ServerPlayer) context.getPlayer()).getAdvancements()); WebDisplays.INSTANCE.criterionLinkPeripheral.trigger(((ServerPlayer) context.getPlayer()).getAdvancements());
} else } else
Util.toast(context.getPlayer(), "linkError"); Util.toast(context.getPlayer(), "linkError");
@ -81,7 +81,7 @@ public class ItemLinker extends Item implements WDItem {
} }
} }
if (!(context.getLevel().getBlockState(context.getClickedPos()).getBlock() instanceof ScreenBlock)) { if(!(context.getLevel().getBlockState(context.getClickedPos()).getBlock() instanceof BlockScreen)) {
Util.toast(context.getPlayer(), "notAScreen"); Util.toast(context.getPlayer(), "notAScreen");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
@ -91,15 +91,15 @@ public class ItemLinker extends Item implements WDItem {
Multiblock.findOrigin(context.getLevel(), pos, side, null); Multiblock.findOrigin(context.getLevel(), pos, side, null);
BlockEntity te = context.getLevel().getBlockEntity(pos.toBlock()); BlockEntity te = context.getLevel().getBlockEntity(pos.toBlock());
if (te == null || !(te instanceof ScreenBlockEntity)) { if(te == null || !(te instanceof TileEntityScreen)) {
Util.toast(context.getPlayer(), "turnOn"); Util.toast(context.getPlayer(), "turnOn");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ScreenData scr = ((ScreenBlockEntity) te).getScreen(side); TileEntityScreen.Screen scr = ((TileEntityScreen) te).getScreen(side);
if(scr == null) if(scr == null)
Util.toast(context.getPlayer(), "turnOn"); Util.toast(context.getPlayer(), "turnOn");
else if ((scr.rightsFor(context.getPlayer()) & ScreenRights.MANAGE_UPGRADES) == 0) else if((scr.rightsFor(context.getPlayer()) & ScreenRights.MANAGE_UPGRADES) == 0)
Util.toast(context.getPlayer(), "restrictions"); Util.toast(context.getPlayer(), "restrictions");
else { else {
tag = new CompoundTag(); tag = new CompoundTag();
@ -120,4 +120,5 @@ public class ItemLinker extends Item implements WDItem {
public String getWikiName(@Nonnull ItemStack is) { public String getWikiName(@Nonnull ItemStack is) {
return is.getItem().getName(is).getString(); return is.getItem().getName(is).getString();
} }
} }

View File

@ -28,88 +28,90 @@ import javax.annotation.Nullable;
import java.util.UUID; import java.util.UUID;
public class ItemMinePad2 extends Item implements WDItem { public class ItemMinePad2 extends Item implements WDItem {
public ItemMinePad2(Properties properties) {
super(properties public ItemMinePad2(Properties properties) {
.stacksTo(1) super(properties
.defaultDurability(0) .stacksTo(1)
.defaultDurability(0)
// .tab(WebDisplays.CREATIVE_TAB) // .tab(WebDisplays.CREATIVE_TAB)
); );
} }
private static String getURL(ItemStack is) { private static String getURL(ItemStack is) {
if (is.getTag() == null || !is.getTag().contains("PadURL")) if (is.getTag() == null || !is.getTag().contains("PadURL"))
return CommonConfig.Browser.homepage; return CommonConfig.Browser.homepage;
else else
return is.getTag().getString("PadURL"); return is.getTag().getString("PadURL");
} }
@Override @Override
@Nonnull @Nonnull
public InteractionResultHolder<ItemStack> use(Level world, Player ply, @Nonnull InteractionHand hand) { public InteractionResultHolder<ItemStack> use(Level world, Player ply, @Nonnull InteractionHand hand) {
ItemStack is = ply.getItemInHand(hand); ItemStack is = ply.getItemInHand(hand);
boolean ok; boolean ok;
if (ply.isShiftKeyDown()) { if (ply.isShiftKeyDown()) {
if (world.isClientSide) if (world.isClientSide)
WebDisplays.PROXY.displaySetPadURLGui(is, getURL(is)); WebDisplays.PROXY.displaySetPadURLGui(is, getURL(is));
ok = true; ok = true;
} else if (is.getTag() != null && is.getTag().contains("PadID")) { } else if (is.getTag() != null && is.getTag().contains("PadID")) {
if (world.isClientSide) if (world.isClientSide)
WebDisplays.PROXY.openMinePadGui(is.getTag().getUUID("PadID")); WebDisplays.PROXY.openMinePadGui(is.getTag().getUUID("PadID"));
ok = true; ok = true;
} else { } else {
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();
String url = getURL(is); String url = getURL(is);
WDNetworkRegistry.INSTANCE.sendToServer(new C2SMessageMinepadUrl(uuid, url)); WDNetworkRegistry.INSTANCE.sendToServer(new C2SMessageMinepadUrl(uuid, url));
is.getOrCreateTag().putUUID("PadID", uuid); is.getOrCreateTag().putUUID("PadID", uuid);
ok = true; ok = true;
} }
return new InteractionResultHolder<>(ok ? InteractionResult.SUCCESS : InteractionResult.PASS, is); return new InteractionResultHolder<>(ok ? InteractionResult.SUCCESS : InteractionResult.PASS, is);
} }
@Override @Override
public boolean onEntityItemUpdate(ItemStack stack, ItemEntity ent) { public boolean onEntityItemUpdate(ItemStack stack, ItemEntity ent) {
if (ent.onGround() && !ent.level().isClientSide) { if (ent.onGround() && !ent.level().isClientSide) {
CompoundTag tag = ent.getItem().getTag(); CompoundTag tag = ent.getItem().getTag();
if (tag != null && tag.contains("ThrowHeight")) { if (tag != null && tag.contains("ThrowHeight")) {
//Delete it, it touched the ground //Delete it, it touched the ground
double height = tag.getDouble("ThrowHeight"); double height = tag.getDouble("ThrowHeight");
UUID thrower = null; UUID thrower = null;
if (tag.contains("ThrowerMSB") && tag.contains("ThrowerLSB")) if (tag.contains("ThrowerMSB") && tag.contains("ThrowerLSB"))
thrower = new UUID(tag.getLong("ThrowerMSB"), tag.getLong("ThrowerLSB")); thrower = new UUID(tag.getLong("ThrowerMSB"), tag.getLong("ThrowerLSB"));
if (tag.contains("PadID") || tag.contains("PadURL")) { if (tag.contains("PadID") || tag.contains("PadURL")) {
tag.remove("ThrowerMSB"); tag.remove("ThrowerMSB");
tag.remove("ThrowerLSB"); tag.remove("ThrowerLSB");
tag.remove("ThrowHeight"); tag.remove("ThrowHeight");
} else //We can delete the whole tag } else //We can delete the whole tag
ent.getItem().setTag(null); ent.getItem().setTag(null);
if (thrower != null && height - ent.getBlockY() >= 20.0) { if (thrower != null && height - ent.getBlockY() >= 20.0) {
ent.level().playSound(null, ent.getBlockX(), ent.getBlockY(), ent.getBlockZ(), SoundEvents.GLASS_BREAK, SoundSource.BLOCKS, 4.0f, 1.0f); ent.level().playSound(null, ent.getBlockX(), ent.getBlockY(), ent.getBlockZ(), SoundEvents.GLASS_BREAK, SoundSource.BLOCKS, 4.0f, 1.0f);
ent.level().addFreshEntity(new ItemEntity(ent.level(), ent.getBlockX(), ent.getBlockY(), ent.getBlockZ(), CraftComponent.EXTCARD.makeItemStack())); ent.level().addFreshEntity(new ItemEntity(ent.level(), ent.getBlockX(), ent.getBlockY(), ent.getBlockZ(), CraftComponent.EXTCARD.makeItemStack()));
ent.setRemoved(Entity.RemovalReason.CHANGED_DIMENSION); ent.setRemoved(Entity.RemovalReason.CHANGED_DIMENSION);
Player ply = ent.level().getPlayerByUUID(thrower); Player ply = ent.level().getPlayerByUUID(thrower);
if (ply != null && ply instanceof ServerPlayer) if (ply != null && ply instanceof ServerPlayer)
WebDisplays.INSTANCE.criterionPadBreak.trigger(((ServerPlayer) ply).getAdvancements()); WebDisplays.INSTANCE.criterionPadBreak.trigger(((ServerPlayer) ply).getAdvancements());
} }
} }
} }
return false; return false;
} }
@Nullable
@Override
public String getWikiName(@Nonnull ItemStack is) {
return is.getItem().getName(is).getString();
}
@Nullable
@Override
public String getWikiName(@Nonnull ItemStack is) {
return is.getItem().getName(is).getString();
}
} }

View File

@ -9,6 +9,7 @@ import net.minecraft.world.item.Item;
import java.util.BitSet; import java.util.BitSet;
public class ItemMulti extends Item { public class ItemMulti extends Item {
protected final Enum[] values; protected final Enum[] values;
protected final BitSet creativeTabItems; protected final BitSet creativeTabItems;

View File

@ -12,57 +12,55 @@ import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.montoyo.wd.block.ScreenBlock; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.block.BlockScreen;
import net.montoyo.wd.config.CommonConfig; import net.montoyo.wd.config.CommonConfig;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity;
import net.montoyo.wd.utilities.*; import net.montoyo.wd.utilities.*;
import net.montoyo.wd.utilities.math.Vector3i;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.serialization.Util;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public class ItemOwnershipThief extends Item implements WDItem { public class ItemOwnershipThief extends Item implements WDItem {
public ItemOwnershipThief(Properties properties) { public ItemOwnershipThief(Properties properties) {
super(properties super(properties
.stacksTo(1) .stacksTo(1)
// .tab(WebDisplays.CREATIVE_TAB) // .tab(WebDisplays.CREATIVE_TAB)
); );
} }
@Override @Override
public @NotNull InteractionResult useOn(UseOnContext context) { public @NotNull InteractionResult useOn(UseOnContext context) {
if (context.getPlayer().isShiftKeyDown()) if(context.getPlayer().isShiftKeyDown())
return InteractionResult.PASS; return InteractionResult.PASS;
if (context.getLevel().isClientSide) if(context.getLevel().isClientSide)
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
if (CommonConfig.disableOwnershipThief) { if(CommonConfig.disableOwnershipThief) {
Util.toast(context.getPlayer(), "otDisabled"); Util.toast(context.getPlayer(), "otDisabled");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ItemStack stack = context.getPlayer().getItemInHand(context.getHand()); ItemStack stack = context.getPlayer().getItemInHand(context.getHand());
if (stack.hasTag()) { if(stack.hasTag()) {
CompoundTag tag = stack.getTag(); CompoundTag tag = stack.getTag();
if (tag.contains("PosX") && tag.contains("PosY") && tag.contains("PosZ") && tag.contains("Side")) { if(tag.contains("PosX") && tag.contains("PosY") && tag.contains("PosZ") && tag.contains("Side")) {
BlockPos bp = new BlockPos(tag.getInt("PosX"), tag.getInt("PosY"), tag.getInt("PosZ")); BlockPos bp = new BlockPos(tag.getInt("PosX"), tag.getInt("PosY"), tag.getInt("PosZ"));
BlockSide side = BlockSide.values()[tag.getByte("Side")]; BlockSide side = BlockSide.values()[tag.getByte("Side")];
if (!(context.getLevel().getBlockState(bp).getBlock() instanceof ScreenBlock)) if(!(context.getLevel().getBlockState(bp).getBlock() instanceof BlockScreen))
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
BlockEntity te = context.getLevel().getBlockEntity(bp); BlockEntity te = context.getLevel().getBlockEntity(bp);
if (te == null || !(te instanceof ScreenBlockEntity)) if(te == null || !(te instanceof TileEntityScreen))
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
ScreenBlockEntity tes = (ScreenBlockEntity) te; TileEntityScreen tes = (TileEntityScreen) te;
ScreenData scr = tes.getScreen(side); TileEntityScreen.Screen scr = tes.getScreen(side);
if(scr == null) if(scr == null)
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
@ -74,20 +72,20 @@ public class ItemOwnershipThief extends Item implements WDItem {
} }
} }
if (!(context.getLevel().getBlockState(context.getClickedPos()).getBlock() instanceof ScreenBlock)) if(!(context.getLevel().getBlockState(context.getClickedPos()).getBlock() instanceof BlockScreen))
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
Vector3i pos = new Vector3i(context.getClickedPos()); Vector3i pos = new Vector3i(context.getClickedPos());
BlockSide side = BlockSide.values()[context.getClickedFace().ordinal()]; BlockSide side = BlockSide.values()[context.getHorizontalDirection().ordinal()];
Multiblock.findOrigin(context.getLevel(), pos, side, null); Multiblock.findOrigin(context.getLevel(), pos, side, null);
BlockEntity te = context.getLevel().getBlockEntity(pos.toBlock()); BlockEntity te = context.getLevel().getBlockEntity(pos.toBlock());
if (te == null || !(te instanceof ScreenBlockEntity)) { if(te == null || !(te instanceof TileEntityScreen)) {
Util.toast(context.getPlayer(), "turnOn"); Util.toast(context.getPlayer(), "turnOn");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
if (((ScreenBlockEntity) te).getScreen(side) == null) if(((TileEntityScreen) te).getScreen(side) == null)
Util.toast(context.getPlayer(), "turnOn"); Util.toast(context.getPlayer(), "turnOn");
else { else {
CompoundTag tag = new CompoundTag(); CompoundTag tag = new CompoundTag();
@ -109,4 +107,5 @@ public class ItemOwnershipThief extends Item implements WDItem {
public String getWikiName(@Nonnull ItemStack is) { public String getWikiName(@Nonnull ItemStack is) {
return "Ownership_Thief"; return "Ownership_Thief";
} }
} }

View File

@ -10,44 +10,45 @@ import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.montoyo.wd.block.ScreenBlock; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.block.BlockScreen;
import net.montoyo.wd.data.ScreenConfigData; import net.montoyo.wd.data.ScreenConfigData;
import net.montoyo.wd.entity.ScreenData; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.utilities.BlockSide;
import net.montoyo.wd.utilities.data.BlockSide;
import net.montoyo.wd.utilities.Multiblock; import net.montoyo.wd.utilities.Multiblock;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import net.montoyo.wd.utilities.math.Vector3i; import net.montoyo.wd.utilities.Vector3i;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class ItemScreenConfigurator extends Item implements WDItem { public class ItemScreenConfigurator extends Item implements WDItem {
public ItemScreenConfigurator(Properties properties) { public ItemScreenConfigurator(Properties properties) {
super(properties super(properties
.stacksTo(1) .stacksTo(1)
// .tab(WebDisplays.CREATIVE_TAB) // .tab(WebDisplays.CREATIVE_TAB)
); );
} }
@Override @Override
public InteractionResult useOn(UseOnContext context) { public InteractionResult useOn(UseOnContext context) {
if (context.getPlayer().isShiftKeyDown() || !(context.getLevel().getBlockState(context.getClickedPos()).getBlock() instanceof ScreenBlock)) if(context.getPlayer().isShiftKeyDown() || !(context.getLevel().getBlockState(context.getClickedPos()).getBlock() instanceof BlockScreen))
return InteractionResult.PASS; return InteractionResult.PASS;
if (context.getLevel().isClientSide) if(context.getLevel().isClientSide)
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
Vector3i origin = new Vector3i(context.getClickedPos()); Vector3i origin = new Vector3i(context.getClickedPos());
BlockSide side = BlockSide.values()[context.getClickedFace().ordinal()]; BlockSide side = BlockSide.values()[context.getHorizontalDirection().getOpposite().ordinal()];
Multiblock.findOrigin(context.getLevel(), origin, side, null); Multiblock.findOrigin(context.getLevel(), origin, side, null);
BlockEntity te = context.getLevel().getBlockEntity(origin.toBlock()); BlockEntity te = context.getLevel().getBlockEntity(origin.toBlock());
if (te == null || !(te instanceof ScreenBlockEntity)) { if(te == null || !(te instanceof TileEntityScreen)) {
Util.toast(context.getPlayer(), "turnOn"); Util.toast(context.getPlayer(), "turnOn");
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
ScreenData scr = ((ScreenBlockEntity) te).getScreen(side); TileEntityScreen.Screen scr = ((TileEntityScreen) te).getScreen(side);
if(scr == null) if(scr == null)
Util.toast(context.getPlayer(), "turnOn"); Util.toast(context.getPlayer(), "turnOn");
else else

View File

@ -7,10 +7,11 @@ package net.montoyo.wd.item;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.core.DefaultUpgrade; import net.montoyo.wd.core.DefaultUpgrade;
import net.montoyo.wd.core.IUpgrade; import net.montoyo.wd.core.IUpgrade;
import net.montoyo.wd.entity.ScreenBlockEntity; import net.montoyo.wd.entity.TileEntityScreen;
import net.montoyo.wd.utilities.data.BlockSide; import net.montoyo.wd.utilities.BlockSide;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@ -25,12 +26,12 @@ public class ItemUpgrade extends ItemMulti implements IUpgrade, WDItem {
} }
@Override @Override
public void onInstall(@Nonnull ScreenBlockEntity tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is) { public void onInstall(@Nonnull TileEntityScreen tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is) {
} }
@Override @Override
public boolean onRemove(@Nonnull ScreenBlockEntity tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is) { public boolean onRemove(@Nonnull TileEntityScreen tes, @Nonnull BlockSide screenSide, @Nullable Player player, @Nonnull ItemStack is) {
if (DefaultUpgrade.LASERMOUSE.matchesLaserMouse(is)) if(DefaultUpgrade.LASERMOUSE.matchesLaserMouse(is))
tes.clearLaserUser(screenSide); tes.clearLaserUser(screenSide);
return false; return false;

View File

@ -14,9 +14,10 @@ import javax.annotation.Nullable;
import java.util.List; import java.util.List;
public interface WDItem { public interface WDItem {
static void addInformation(@Nullable List<String> tt) { static void addInformation(@Nullable List<String> tt) {
if (tt != null && WebDisplays.PROXY.isShiftDown()) if(tt != null && WebDisplays.PROXY.isShiftDown())
tt.add(ChatFormatting.GRAY + I18n.get("item.webdisplays.wiki")); tt.add("" + ChatFormatting.GRAY + I18n.get("item.webdisplays.wiki"));
} }
String getWikiName(@Nonnull ItemStack is); String getWikiName(@Nonnull ItemStack is);

View File

@ -9,7 +9,7 @@ import net.minecraft.world.entity.player.Player;
import net.montoyo.wd.miniserv.*; import net.montoyo.wd.miniserv.*;
import net.montoyo.wd.net.server_bound.C2SMessageMiniservConnect; import net.montoyo.wd.net.server_bound.C2SMessageMiniservConnect;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import javax.crypto.*; import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;

View File

@ -51,7 +51,7 @@ public class ClientTaskCheckFile extends ClientTask<ClientTaskCheckFile> {
public String getURL() { public String getURL() {
try { try {
return ((new StringBuilder("webdisplays://"))).append(uuid.toString()).append('/').append(URLEncoder.encode(fname, "UTF-8")).toString(); return ((new StringBuilder("wd://"))).append(uuid.toString()).append('/').append(URLEncoder.encode(fname, "UTF-8")).toString();
} catch(UnsupportedEncodingException ex) { } catch(UnsupportedEncodingException ex) {
ex.printStackTrace(); ex.printStackTrace();
return "hi"; return "hi";

View File

@ -8,7 +8,7 @@ import net.montoyo.wd.miniserv.Constants;
import net.montoyo.wd.miniserv.OutgoingPacket; import net.montoyo.wd.miniserv.OutgoingPacket;
import net.montoyo.wd.miniserv.PacketID; import net.montoyo.wd.miniserv.PacketID;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;

View File

@ -6,7 +6,7 @@ package net.montoyo.wd.miniserv.server;
import net.montoyo.wd.WebDisplays; import net.montoyo.wd.WebDisplays;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;

View File

@ -6,7 +6,7 @@ package net.montoyo.wd.miniserv.server;
import net.montoyo.wd.miniserv.*; import net.montoyo.wd.miniserv.*;
import net.montoyo.wd.utilities.Log; import net.montoyo.wd.utilities.Log;
import net.montoyo.wd.utilities.serialization.Util; import net.montoyo.wd.utilities.Util;
import java.io.*; import java.io.*;
import java.nio.channels.ClosedChannelException; import java.nio.channels.ClosedChannelException;

View File

@ -4,7 +4,7 @@ import net.minecraft.client.Minecraft;
import net.minecraft.client.MouseHandler; import net.minecraft.client.MouseHandler;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
import net.minecraft.world.phys.HitResult; import net.minecraft.world.phys.HitResult;
import net.montoyo.wd.registry.ItemRegistry; import net.montoyo.wd.init.ItemInit;
import net.montoyo.wd.item.ItemLaserPointer; import net.montoyo.wd.item.ItemLaserPointer;
import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
@ -15,23 +15,21 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(MouseHandler.class) @Mixin(MouseHandler.class)
public class MouseHandlerMixin { public class MouseHandlerMixin {
@Shadow @Shadow @Final private Minecraft minecraft;
@Final
private Minecraft minecraft;
@Inject(at = @At("HEAD"), method = "onPress", cancellable = true) @Inject(at = @At("HEAD"), method = "onPress", cancellable = true)
public void prePress(long p_91531_, int p_91532_, int p_91533_, int p_91534_, CallbackInfo ci) { public void prePress(long p_91531_, int p_91532_, int p_91533_, int p_91534_, CallbackInfo ci) {
boolean flag = p_91533_ == 1; boolean flag = p_91533_ == 1;
if (Minecraft.getInstance().screen == null) { if (Minecraft.getInstance().screen == null) {
if ( if (
minecraft.player != null && minecraft.level != null && minecraft.player != null && minecraft.level != null &&
minecraft.player.getItemInHand(InteractionHand.MAIN_HAND).getItem().equals(ItemRegistry.LASER_POINTER.get()) && minecraft.player.getItemInHand(InteractionHand.MAIN_HAND).getItem().equals(ItemInit.LASER_POINTER.get()) &&
(minecraft.hitResult == null || minecraft.hitResult.getType() == HitResult.Type.BLOCK || minecraft.hitResult.getType() == HitResult.Type.MISS) (minecraft.hitResult == null || minecraft.hitResult.getType() == HitResult.Type.BLOCK || minecraft.hitResult.getType() == HitResult.Type.MISS)
) { ) {
ItemLaserPointer.press(flag, p_91532_); ItemLaserPointer.press(flag, p_91532_);
ci.cancel(); ci.cancel();
} }
} }
} }
} }

View File

@ -14,19 +14,19 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Gui.class) @Mixin(Gui.class)
public class OverlayMixin { public class OverlayMixin {
@Shadow @Shadow
@Final @Final
protected Minecraft minecraft; protected Minecraft minecraft;
@Shadow @Shadow
protected int screenWidth; protected int screenWidth;
@Shadow @Shadow
protected int screenHeight; protected int screenHeight;
@Inject(at = @At("HEAD"), method = "renderCrosshair", cancellable = true) @Inject(at = @At("HEAD"), method = "renderCrosshair", cancellable = true)
public void preDrawCrosshair(GuiGraphics pGuiGraphics, CallbackInfo ci) { public void preDrawCrosshair(GuiGraphics pGuiGraphics, CallbackInfo ci) {
// ClientProxy.renderCrosshair(minecraft.options, screenWidth, screenHeight, ((Gui) (Object) this).getBlitOffset(), poseStack, ci); // ClientProxy.renderCrosshair(minecraft.options, screenWidth, screenHeight, ((Gui) (Object) this).getBlitOffset(), poseStack, ci);
ClientProxy.renderCrosshair(minecraft.options, screenWidth, screenHeight, 0, pGuiGraphics, ci); ClientProxy.renderCrosshair(minecraft.options, screenWidth, screenHeight, 0, pGuiGraphics, ci);
} }
} }

Some files were not shown because too many files have changed in this diff Show More