Merge pull request #4 from cire3wastaken/main

feat: Optimize OBJ Converter, and some more minor features, as well as update to use Gradle
This commit is contained in:
lax1dude 2024-06-22 12:51:12 -07:00 committed by GitHub
commit 1f78267d91
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 823 additions and 52 deletions

6
.gitignore vendored
View File

@ -1,3 +1,9 @@
.classpath
.project
bin
.idea
samples/obj2mdl-fnaw/output
samples/obj2mdl-fnaw/tests
build
.gradle

Binary file not shown.

View File

@ -163,6 +163,6 @@ Mipmap levels will be generated automatically and embedded in the Eagler BMP fil
## Compiling and Contributing
The code in the `src/main/java` folder is written in plain Java. There are no dependencies besides what is already included by default in the JRE. Minimum required Java version is 8, just compile to JAR and you're ready to go.
The code in the `src/main/java` folder is written in plain Java. There are no dependencies besides what is already included by default in the JRE & JUnit for tests. Minimum required Java version is 8, just run `gradlew build`.
**For a PR:** Tabs, not spaces, and format the code like the Eclipse auto format tool on factory settings.

43
build.gradle Normal file
View File

@ -0,0 +1,43 @@
plugins {
id 'java'
}
group = 'net.lax1dude.eaglercraft.bintools'
version = ''
repositories {
mavenCentral()
}
sourceSets {
main {
java {
srcDir 'src/main/java'
}
}
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.2'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.10.2'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.10.2'
}
jar {
sourceCompatibility = 1.8
targetCompatibility = 1.8
compileJava.options.encoding = 'UTF-8'
javadoc.options.encoding = 'UTF-8'
javadoc.options.addStringOption('Xdoclint:none', '-quiet')
manifest {
attributes(
'Main-Class': 'net.lax1dude.eaglercraft.bintools.EaglerBinaryTools'
)
}
}
test {
useJUnitPlatform()
}

18
generate_mdl_samples.bat Normal file
View File

@ -0,0 +1,18 @@
@echo off
title Generate_MDLs
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/charles0.obj samples/obj2mdl-fnaw/output/charles0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/charles1.obj samples/obj2mdl-fnaw/output/charles1.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/charles2_eyes.obj samples/obj2mdl-fnaw/output/charles2.mdl false
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/laxativedude0.obj samples/obj2mdl-fnaw/output/laxativedude0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/laxativedude1.obj samples/obj2mdl-fnaw/output/laxativedude1.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/laxativedude2.obj samples/obj2mdl-fnaw/output/laxativedude2.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/laxativedude3_eyes.obj samples/obj2mdl-fnaw/output/laxativedude3.mdl false
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/longarms0.obj samples/obj2mdl-fnaw/output/longarms0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/longarms1.obj samples/obj2mdl-fnaw/output/longarms1.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/longarms2_eyes.obj samples/obj2mdl-fnaw/output/longarms2.mdl false
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/weirdclimber0.obj samples/obj2mdl-fnaw/output/weirdclimber0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/weirdclimber1.obj samples/obj2mdl-fnaw/output/weirdclimber1.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/weirdclimber2_eyes.obj samples/obj2mdl-fnaw/output/weirdclimber2.mdl false
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/winston0.obj samples/obj2mdl-fnaw/output/winston0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/winston1_eyes.obj samples/obj2mdl-fnaw/output/winston1.mdl false
pause

16
generate_mdl_samples.sh Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/charles0.obj samples/obj2mdl-fnaw/output/charles0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/charles1.obj samples/obj2mdl-fnaw/output/charles1.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/charles2_eyes.obj samples/obj2mdl-fnaw/output/charles2.mdl false
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/laxativedude0.obj samples/obj2mdl-fnaw/output/laxativedude0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/laxativedude1.obj samples/obj2mdl-fnaw/output/laxativedude1.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/laxativedude2.obj samples/obj2mdl-fnaw/output/laxativedude2.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/laxativedude3_eyes.obj samples/obj2mdl-fnaw/output/laxativedude3.mdl false
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/longarms0.obj samples/obj2mdl-fnaw/output/longarms0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/longarms1.obj samples/obj2mdl-fnaw/output/longarms1.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/longarms2_eyes.obj samples/obj2mdl-fnaw/output/longarms2.mdl false
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/weirdclimber0.obj samples/obj2mdl-fnaw/output/weirdclimber0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/weirdclimber1.obj samples/obj2mdl-fnaw/output/weirdclimber1.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/weirdclimber2_eyes.obj samples/obj2mdl-fnaw/output/weirdclimber2.mdl false
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/winston0.obj samples/obj2mdl-fnaw/output/winston0.mdl true
java -jar EaglerBinaryTools.jar obj2mdl1.8 samples/obj2mdl-fnaw/winston1_eyes.obj samples/obj2mdl-fnaw/output/winston1.mdl false

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Thu Jun 20 10:14:47 CDT 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

2
settings.gradle Normal file
View File

@ -0,0 +1,2 @@
rootProject.name = 'EaglerBinaryTools'

View File

@ -38,14 +38,37 @@ public class EaglerBinaryTools {
case "epkdecompiler":
EPKDecompiler._main(argz);
return;
case "obj2mdl-1.5":
case "obj2mdl1.5":
case "obj2mdl-1.5-old":
case "obj2mdl-1.5old":
case "obj2mdl1.5-old":
case "obj2mdl1.5old":
OBJConverter._main(argz, false);
return;
case "obj2mdl-1.8-old":
case "obj2mdl-1.8old":
case "obj2mdl1.8-old":
case "obj2mdl-old":
case "obj2mdlold":
OBJConverter._main(argz, true);
return;
case "obj2mdl-1.5-new":
case "obj2mdl-1.5new":
case "obj2mdl1.5-new":
case "obj2mdl1.5new":
case "obj2mdl-1.5":
case "obj2mdl1.5":
OptimizedOBJConverter._main(argz, false);
return;
case "obj2mdl-1.8-new":
case "obj2mdl-1.8new":
case "obj2mdl1.8-new":
case "obj2mdl1.8new":
case "obj2mdl-new":
case "obj2mdlnew":
case "obj2mdl-1.8":
case "obj2mdl1.8":
case "obj2mdl":
OBJConverter._main(argz, true);
OptimizedOBJConverter._main(argz, true);
return;
case "ebp-encode":
case "ebpencode":
@ -84,6 +107,8 @@ public class EaglerBinaryTools {
System.out.println(" - 'epkdecompiler': Decompile an EPK file into a folder");
System.out.println(" - 'obj2mdl-1.5': Compile FNAW skin MDL file for 1.5");
System.out.println(" - 'obj2mdl-1.8': Compile FNAW skin MDL file for 1.8");
System.out.println(" - 'obj2mdl-1.5-old': Compile FNAW skin MDL file for 1.5 using the old OBJ converter");
System.out.println(" - 'obj2mdl-1.8-old': Compile FNAW skin MDL file for 1.8 using the old OBJ converter");
System.out.println(" - 'ebp-encode': Encode EBP file from PNG");
System.out.println(" - 'ebp-decode': Decode EBP file to PNG");
System.out.println(" - 'skybox-gen': Generate skybox.dat from OBJ for shader packs");

View File

@ -28,6 +28,7 @@ import java.util.List;
* POSSIBILITY OF SUCH DAMAGE.
*
*/
@Deprecated
public class OBJConverter {
public static void _main(String[] args, boolean v1_8) throws IOException {
@ -48,7 +49,14 @@ public class OBJConverter {
File output = new File(args[1]);
System.out.println("Exporting " + (v1_8 ? "1.8" : "1.5") + " MDL: " + output.getAbsolutePath());
boolean tex = args[2].equalsIgnoreCase("true") || args[2].equals("1");
try(FileOutputStream fs = new FileOutputStream(output)) {
if (!output.exists()) {
if (!output.getParentFile().exists())
if (!output.getParentFile().mkdirs())
throw new RuntimeException("Failed to create parent dir!");
if (!output.createNewFile())
throw new RuntimeException("Failed to create file!");
}
try(FileOutputStream fs = new FileOutputStream(output, false)) {
convertModel(lns, fs, tex, v1_8);
}
if(tex) {

View File

@ -0,0 +1,285 @@
package net.lax1dude.eaglercraft.bintools;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class OptimizedOBJConverter {
public static void _main(String[] args, boolean v1_8) throws IOException {
if(args.length != 3) {
System.out.println("Usage: obj2mdl-" + (v1_8 ? "1.8" : "1.5") + " <input file> <output file> <texture mode>");
System.out.println("Input file format is Wavefront OBJ file exported from your 3D modeling program");
System.out.println("Texture mode can be 'true' or 'false' to enable/disable exporting texture UV coordinates");
return;
}
System.out.println("Reading input file...");
List<String> lns = new ArrayList();
try(BufferedReader bu = new BufferedReader(new FileReader(new File(args[0])))) {
String s;
while((s = bu.readLine()) != null) {
lns.add(s);
}
}
File output = new File(args[1]);
System.out.println("Exporting " + (v1_8 ? "1.8" : "1.5") + " MDL: " + output.getAbsolutePath());
boolean tex = args[2].equalsIgnoreCase("true") || args[2].equals("1");
if (!output.exists()) {
if (!output.getParentFile().exists())
if (!output.getParentFile().mkdirs())
throw new RuntimeException("Failed to create parent dir!");
if (!output.createNewFile())
throw new RuntimeException("Failed to create file!");
}
try(FileOutputStream fs = new FileOutputStream(output)) {
convertModel(lns, fs, tex, v1_8);
}
if(tex) {
System.out.println("Export with UVs completed!");
}else {
System.out.println("Export without UVs competed!");
}
}
public static void convertModel(Collection<String> lines, OutputStream out, boolean textureMode, boolean v1_8) throws IOException {
List<float[]> vertexes = new ArrayList<float[]>();
List<byte[]> normals = new ArrayList<byte[]>();
List<float[]> texcoords = new ArrayList<float[]>();
List<int[][]> faces = new ArrayList<int[][]>();
List<byte[]> vboentries = new ArrayList<byte[]>();
IndexLinkedHashSet<ByteArray> indexablevboentries = new IndexLinkedHashSet<>();
List<Integer> indexbuffer = new ArrayList<Integer>();
for(String ul : lines) {
String[] l = ul.split(" ");
if(l[0].equals("v")) {
vertexes.add(new float[] {Float.parseFloat(l[1]), Float.parseFloat(l[2]), Float.parseFloat(l[3])});
}
if(l[0].equals("vn")) {
int dumb = v1_8 ? 0 : 127;
normals.add(new byte[] {(byte)((int)(Float.parseFloat(l[1]) * 127.0F) + dumb), (byte)((int)(Float.parseFloat(l[2]) * 127.0F) + dumb), (byte)((int)(Float.parseFloat(l[3]) * 127.0F) + dumb), (byte)0});
}
if(textureMode) {
if(l[0].equals("vt")) {
texcoords.add(new float[] {Float.parseFloat(l[1]), 1.0f - Float.parseFloat(l[2])});
}
}
if(l[0].equals("f")) {
if(l.length != 4) {
printTriangulationMessage();
throw new IOException("Incompatible model! (This can be fixed)");
}
String[] v1 = l[1].split("/");
String[] v2 = l[2].split("/");
String[] v3 = l[3].split("/");
faces.add(new int[][] {
{Integer.parseInt(v1[0]), Integer.parseInt(v1[1]), Integer.parseInt(v1[2])},
{Integer.parseInt(v2[0]), Integer.parseInt(v2[1]), Integer.parseInt(v2[2])},
{Integer.parseInt(v3[0]), Integer.parseInt(v3[1]), Integer.parseInt(v3[2])}
});
}
}
for(int[][] f : faces) {
for(int i = 0; i < 3; i++) {
byte[] b = new byte[textureMode ? 24 : 16];
float[] v = vertexes.get(f[i][0]-1);
int ix = Float.floatToRawIntBits(v[0]);
int iy = Float.floatToRawIntBits(v[1]);
int iz = Float.floatToRawIntBits(v[2]);
int idx = 0;
b[idx++] = (byte)(ix); b[idx++] = (byte)(ix >> 8); b[idx++] = (byte)(ix >> 16); b[idx++] = (byte)(ix >> 24);
b[idx++] = (byte)(iy); b[idx++] = (byte)(iy >> 8); b[idx++] = (byte)(iy >> 16); b[idx++] = (byte)(iy >> 24);
b[idx++] = (byte)(iz); b[idx++] = (byte)(iz >> 8); b[idx++] = (byte)(iz >> 16); b[idx++] = (byte)(iz >> 24);
byte[] n = normals.get(f[i][2]-1);
b[idx++] = n[0];
b[idx++] = n[1];
b[idx++] = n[2];
b[idx++] = n[3];
if(textureMode) {
float[] t = texcoords.get(f[i][1]-1);
int ix3 = Float.floatToRawIntBits(t[0]);
int iy3 = Float.floatToRawIntBits(t[1]);
b[idx++] = (byte)(ix3); b[idx++] = (byte)(ix3 >> 8); b[idx++] = (byte)(ix3 >> 16); b[idx++] = (byte)(ix3 >> 24);
b[idx++] = (byte)(iy3); b[idx++] = (byte)(iy3 >> 8); b[idx++] = (byte)(iy3 >> 16); b[idx++] = (byte)(iy3 >> 24);
}
vboentries.add(b);
}
}
for (byte[] v : vboentries) {
int l = indexablevboentries.size();
// HashSet is amortized constant time for contains
// (IndexLinkedHashSet is backed by an arraylist for indices and a HashSet for performance)
if (indexablevboentries.contains(ByteArray.of(v))) {
indexbuffer.add(indexablevboentries.indexOf(ByteArray.of(v)));
} else {
if (l > 65535)
throw new RuntimeException("Too many vertices!");
indexbuffer.add(l);
indexablevboentries.add(ByteArray.of(v));
}
}
DataOutputStream o = new DataOutputStream(out);
o.write((v1_8 ? "!EAG$mdl" : "!EAG%mdl").getBytes(StandardCharsets.US_ASCII));
o.write(textureMode ? (byte)'T' : (byte)'C');
o.writeUTF("\n\nthis file was generated with EaglerBinaryTools\n\n");
o.writeInt(indexablevboentries.size());
o.writeInt(indexbuffer.size());
for(int i = 0; i < indexablevboentries.size(); ++i) {
byte[] b = indexablevboentries.get(i).array;
o.write(b, 0, b.length);
}
for(int i : indexbuffer) {
o.write((byte)i);
o.write((byte)(i >> 8));
}
o.write("_:>+".getBytes(StandardCharsets.US_ASCII));
o.close();
}
static void printTriangulationMessage() {
System.err.println("=====================================");
System.err.println("THIS OBJ FILE IS NOT COMPATIBLE WITH EAGLERCRAFT!");
System.err.println();
System.err.println("Eaglercraft meshes can only have triangles in them.");
System.err.println();
System.err.println("If you're using Blender, add the \"triangulate\"");
System.err.println("modifier to the mesh before exporting to fix");
System.err.println("=====================================");
}
/*
* Copied from https://stackoverflow.com/a/77179230
* */
public static final class IndexLinkedHashSet<E> implements Set<E> {
private final ArrayList<E> list = new ArrayList<>( );
private final HashSet<E> set = new HashSet<> ( );
public synchronized boolean add(E e) {
if ( set.add(e) ) {
return list.add(e);
}
return false;
}
public synchronized boolean remove(Object o) {
if ( set.remove(o) ) {
return list.remove(o);
}
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
return set.containsAll(c);
}
public synchronized void clear() {
set.clear();
list.clear();
}
public synchronized E get(int index) {
return list.get(index);
}
// Added this function
public synchronized int indexOf(E element) {
return list.indexOf(element);
}
//
public synchronized boolean removeAll(Collection<?> c) {
if ( set.removeAll(c) ) {
return list.removeAll(c);
}
return true;
}
public synchronized boolean retainAll(Collection<?> c) {
if ( set.retainAll(c) ) {
return list.retainAll(c);
}
return false;
}
public synchronized boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
@Override
public synchronized int size() {
return set.size();
}
@Override
public synchronized boolean isEmpty() {
return set.isEmpty();
}
@Override
public synchronized boolean contains(Object o) {
return set.contains(o);
}
@Override
public synchronized Iterator<E> iterator() {
return list.iterator();
}
@Override
public synchronized Object[] toArray() {
return list.toArray();
}
@Override
public synchronized <T> T[] toArray(T[] a) {
return list.toArray(a);
}
}
public static class ByteArray {
public final byte[] array;
public ByteArray(byte[] array) {
this.array = array;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ByteArray byteArray = (ByteArray) o;
return Arrays.equals(array, byteArray.array);
}
@Override
public int hashCode() {
return Arrays.hashCode(array);
}
public static ByteArray of(byte... bytes) {
return new ByteArray(bytes);
}
}
}

View File

@ -0,0 +1,39 @@
package net.lax1dude.eaglercraft.bintools;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.annotation.Testable;
import java.io.FileInputStream;
import java.io.IOException;
@Testable
public class TestOptimizedOBJConverter {
@Test
@SuppressWarnings("ConstantConditions")
public void test() throws IOException {
String[] paramz = {
"samples/obj2mdl-fnaw/laxativedude1.obj", "samples/obj2mdl-fnaw/tests/output/laxativedude1.mdl", "true"
};
OBJConverter._main(paramz, true);
paramz[1] = "samples/obj2mdl-fnaw/tests/output/o_laxativedude1.mdl";
OptimizedOBJConverter._main(paramz, true);
try (FileInputStream optimizedProgramOutput = new FileInputStream(paramz[1]);
FileInputStream originalProgramOutput = new FileInputStream( "samples/obj2mdl-fnaw/tests/output/laxativedude1.mdl")) {
int o;
int r;
while ((o = optimizedProgramOutput.read()) != -2 && (r = originalProgramOutput.read()) != -2) {
if (o == r && r == -1)
break;
if (o != r)
Assertions.fail("Output is not the same!");
}
} catch (Exception e) {
Assertions.fail(e.getMessage());
}
}
}