Skip to content

Commit

Permalink
it works
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhuRuoLing committed Mar 29, 2024
1 parent 27ef1c4 commit 64d4039
Show file tree
Hide file tree
Showing 11 changed files with 389 additions and 46 deletions.
70 changes: 62 additions & 8 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ plugins {
id 'java-library'
id 'eclipse'
id 'maven-publish'
id 'checkstyle'
// id 'checkstyle'
id 'com.diffplug.spotless' version "6.22.0"
id 'fabric-loom' version '1.4-SNAPSHOT' apply false
id 'com.github.johnrengelman.shadow' version '8.1.1'
Expand Down Expand Up @@ -179,9 +179,63 @@ task getSat4jAbout(type: Copy) {
into layout.buildDirectory.dir("sat4j")
}

tasks.getByName("build").dependsOn("distZip")

task copyLibraries(type: Copy){
dependsOn "fatJar"
delete(layout.buildDirectory.dir("packed"))
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
layout.buildDirectory.dir("libs/").collect {
def files = it.get().asFileTree.files
for (final def f in files) {
if (f.name.contains "fat"){
from f.toPath().toAbsolutePath().toString()
}
}
}
configurations.runtimeClasspath.each {
from it.toPath().toAbsolutePath().toString()
}

into layout.buildDirectory.dir("packed/libs")
}

def startBatContent = [
"@echo off",
"@rem Set your velocity jar name into system property fabric.systemLibraryExclusion",
"java \"-Dfabric.systemLibraryExclusion=velocity-3.3.0-SNAPSHOT-371.jar\" \"-Dfabric.debug.disableClassPathIsolation\" -cp \"./libs/*\" net.fabricmc.loader.impl.launch.knot.KnotServer\n",
"pause"
]

def startShContent = [
"#!/bin/sh",
"java \"-Dfabric.systemLibraryExclusion=velocity-3.3.0-SNAPSHOT-371.jar\" \"-Dfabric.debug.disableClassPathIsolation\" -cp \"./libs/*\" net.fabricmc.loader.impl.launch.knot.KnotServer\n"
]

tasks.register("generateStartScript"){
dependsOn "copyLibraries"
doLast {
def startBat = layout.buildDirectory.dir("packed").get().file("start.bat")
def startShellScript = layout.buildDirectory.dir("packed").get().file("start.sh")
startBat.asFile.write(startBatContent.join("\n"))
startShellScript.asFile.write(startShContent.join("\n"))
copy {
from layout.projectDirectory.file("README.md")
into layout.buildDirectory.dir("packed")
}
}
}

task distZip(type: Zip){
dependsOn "generateStartScript"
archiveBaseName = "${project.name}-${project.version}-packed"
destinationDirectory = layout.buildDirectory.dir("dist")
from layout.buildDirectory.dir("packed")
}

task fatJar(type: ShadowJar, dependsOn: getSat4jAbout) {
from sourceSets.main.output
from project(":minecraft").sourceSets.main.output
from project(":velocity").sourceSets.main.output
from getSat4jAbout.destinationDir
from("LICENSE") {
rename { "${it}_${project.base.archivesName.get()}"}
Expand Down Expand Up @@ -220,7 +274,7 @@ File proguardFile = file("build/libs/fabric-loader-${version}.jar")

import proguard.gradle.ProGuardTask
task proguardJar(type: ProGuardTask, dependsOn: fatJar) {
def classpath = project(":minecraft").configurations.compileClasspath
def classpath = project(":velocity").configurations.compileClasspath

inputs.files(fatJar, classpath)
outputs.files(proguardFile)
Expand All @@ -246,7 +300,7 @@ tasks.withType(AbstractArchiveTask) {

sourcesJar {
from sourceSets.main.allSource
from project(":minecraft").sourceSets.main.allSource
from project(":velocity").sourceSets.main.allSource
}

// useful for creating test mod jar
Expand Down Expand Up @@ -317,10 +371,10 @@ task javadocJar(type: Jar) {
build.dependsOn javadocJar

allprojects {
checkstyle {
configFile = project.rootProject.file("checkstyle.xml")
toolVersion = '8.44'
}
// checkstyle {
// configFile = project.rootProject.file("checkstyle.xml")
// toolVersion = '8.44'
// }

spotless {
java {
Expand Down
7 changes: 0 additions & 7 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,9 @@ pluginManagement {
}
rootProject.name='fabric-loader'

include "minecraft"
include "velocity"
include "junit"

if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_17)) {
include "minecraft:minecraft-test"
} else {
println("Minecraft test sub project requires java 17 or higher!")
}

if (JavaVersion.current().isCompatibleWith(JavaVersion.VERSION_17)) {
include "velocity:velocity-test"
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright 2016 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.loader.impl.game.velocity;

import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.impl.FabricLoaderImpl;

import java.io.File;

public class Hooks {
public static final String INTERNAL_NAME = Hooks.class.getName().replace('.', '/');

public static void startServer(File runDir, Object gameInstance) {
if (runDir == null) {
runDir = new File(".");
}
if (!gameInstance.getClass().getName().endsWith("VelocityServer")){
throw new RuntimeException("Expected VelocityServer as gameInstance, got " + gameInstance.getClass());
}
FabricLoaderImpl loader = FabricLoaderImpl.INSTANCE;
loader.prepareModInit(runDir.toPath(), gameInstance);
loader.invokeEntrypoints("main", ModInitializer.class, ModInitializer::onInitialize);
loader.invokeEntrypoints("server", DedicatedServerModInitializer.class, DedicatedServerModInitializer::onInitializeServer);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,21 @@

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringBufferInputStream;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Map;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;

import net.fabricmc.loader.impl.util.ExceptionUtil;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
Expand All @@ -48,9 +55,22 @@ public boolean shouldLog(LogLevel level, LogCategory category) {
@Override
public void log(long time, LogLevel level, LogCategory category, String msg, Throwable exc, boolean fromReplay, boolean wasSuppressed) {
// TODO: suppress console log output if wasSuppressed is false to avoid duplicate output
getLogger(category).log(translateLogLevel(level), msg, exc);
// Velocity's logger ignoreException by default
if (exc != null) {
getLogger(category).log(translateLogLevel(level), String.format("%s\n%s", msg, stacktraceToString(exc)));
} else {
getLogger(category).log(translateLogLevel(level), msg);
}
}

private static String stacktraceToString(Throwable tr) {
var os = new ByteArrayOutputStream();
var ps = new PrintStream(os);
tr.printStackTrace(ps);
return os.toString(StandardCharsets.UTF_8);
}


private static Logger getLogger(LogCategory category) {
Logger ret = (Logger) category.data;

Expand All @@ -69,11 +89,12 @@ private static Level translateLogLevel(LogLevel level) {
if (level == LogLevel.DEBUG) return Level.DEBUG;
if (level == LogLevel.TRACE) return Level.TRACE;

throw new IllegalArgumentException("unknown log level: "+level);
throw new IllegalArgumentException("unknown log level: " + level);
}

@Override
public void close() { }
public void close() {
}

static {
if (needsLookupRemoval()) {
Expand Down Expand Up @@ -133,7 +154,8 @@ private static void removeSubstitutionLookups(boolean ignoreMissing) {

try {
LoggerContext context = LogManager.getContext(false);
if (context.getClass().getName().equals("org.apache.logging.log4j.simple.SimpleLoggerContext")) return; // -> no log4j core
if (context.getClass().getName().equals("org.apache.logging.log4j.simple.SimpleLoggerContext"))
return; // -> no log4j core

Object config = context.getClass().getMethod("getConfiguration").invoke(context);
Object substitutor = config.getClass().getMethod("getStrSubstitutor").invoke(config);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*
* Copyright 2016 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.loader.impl.game.velocity;

import net.fabricmc.api.EnvType;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,38 @@
/*
* Copyright 2016 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.loader.impl.game.velocity;

import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import com.google.common.base.MoreObjects;
import com.velocitypowered.api.util.ProxyVersion;

import com.velocitypowered.proxy.VelocityServer;

import net.fabricmc.api.EnvType;
Expand All @@ -12,6 +42,8 @@
import net.fabricmc.loader.impl.game.GameProvider;
import net.fabricmc.loader.impl.game.LibClassifier;
import net.fabricmc.loader.impl.game.patch.GameTransformer;
import net.fabricmc.loader.impl.game.velocity.patch.EntrypointPatch;
import net.fabricmc.loader.impl.game.velocity.patch.TerminalConsoleAppenderPatch;
import net.fabricmc.loader.impl.launch.FabricLauncher;
import net.fabricmc.loader.impl.metadata.BuiltinModMetadata;
import net.fabricmc.loader.impl.metadata.ModDependencyImpl;
Expand All @@ -21,24 +53,9 @@
import net.fabricmc.loader.impl.util.log.Log;
import net.fabricmc.loader.impl.util.log.LogHandler;

import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.PrimitiveIterator;
import java.util.Set;

public class VelocityGameProvider implements GameProvider {

//
private static final String[] ALLOWED_EARLY_CLASS_PREFIXES = {
"org.apache.logging.log4j.",
"com.velocitypowered.",
Expand All @@ -61,7 +78,7 @@ public class VelocityGameProvider implements GameProvider {
private boolean slf4jAvailable;
private String entrypoint;
private Arguments arguments;
private final GameTransformer transformer = new GameTransformer();
private final GameTransformer transformer = new GameTransformer(new EntrypointPatch(), new TerminalConsoleAppenderPatch());

@Override
public String getGameId() {
Expand Down Expand Up @@ -179,6 +196,9 @@ private void lookupVersion(){

@Override
public void initialize(FabricLauncher launcher) {
// some weird workarounds
System.setProperty("fabric.debug.disableClassPathIsolation","");

launcher.setValidParentClassPath(validParentClassPath);
if (!logJars.isEmpty() && !Boolean.getBoolean(SystemProperties.UNIT_TEST)) {
for (Path jar : logJars) {
Expand All @@ -191,6 +211,7 @@ public void initialize(FabricLauncher launcher) {
}

setupLogHandler(launcher, true);
transformer.locateEntrypoints(launcher, gameJars);
}

private void setupLogHandler(FabricLauncher launcher, boolean useTargetCl) {
Expand Down Expand Up @@ -231,18 +252,16 @@ public GameTransformer getEntrypointTransformer() {

@Override
public void unlockClassPath(FabricLauncher launcher) {

for (Path gameJar : gameJars) {

launcher.getKnotClassLoaderDelegate().setAllowedPrefixes(gameJar);
launcher.addToClassPath(gameJar);
}

for (Path lib : miscGameLibraries) {
launcher.addToClassPath(lib);
launcher.getKnotClassLoaderDelegate().addCodeSource(lib);
launcher.getKnotClassLoaderDelegate().setAllowedPrefixes(lib, new String[0]);
}
// how???
// for (Path lib : miscGameLibraries) {
// launcher.addToClassPath(lib);
// launcher.getKnotClassLoaderDelegate().addCodeSource(lib);
// launcher.getKnotClassLoaderDelegate().setAllowedPrefixes(lib, new String[0]);
// }
}

@Override
Expand Down
Loading

0 comments on commit 64d4039

Please sign in to comment.