Compare commits

..

15 Commits

Author SHA1 Message Date
opfromthestart
71250104ea Better 3d falling
-Sand now can fall from and to the direction of gravity
-Registers every FallingBlock block to a different value. It doesnt
quite work though
-Removed unused code
2021-09-10 16:20:09 -04:00
opfromthestart
51752f95f9
Merge pull request #15 from opfromthestart/falling-block
Falling block
2021-08-23 13:35:58 -04:00
opfromthestart
175f092673 Fixed some stuff
-Added default gravity block check in server
-Some things I had to copy since i didnt merge right
-Adds all gravity blocks to FallingBlock list
-LogTop debug thing to check for good textures
-Some texture rendering(see above)
-Some control changes since I need to get to the edge quickly
2021-08-23 13:33:18 -04:00
opfromthestart
59129f95c9 Why
-Idk this has to be "Sand" and not "Test:Sand"
2021-08-22 14:04:42 -04:00
opfromthestart
efff41a6db Merge branch 'master' into falling-block 2021-08-22 14:03:31 -04:00
opfromthestart
30879a1241
Merge pull request #1 from OLEGSHA/master
Uhhh pull
2021-08-22 13:47:54 -04:00
opfromthestart
dccfcc9419 Better /Stuff
-Uses Coordinates a little in TestWorldGenerator. Ill do more eventually I think
-Better sprite getting for FallingBlocks
2021-08-03 15:05:05 -04:00
opfromthestart
c2a2cc074a Some Stuff to Fix Bugs
-Improved debug info of Fallingblock ticking
-Fixed unsynchronized access as per OLEGSHA
-Maybe better server side deletion of blocks
2021-08-03 14:45:36 -04:00
opfromthestart
e58007ea11 Format
Format
2021-06-10 17:09:24 -04:00
opfromthestart
ae2980c9de Bug Fixing and Performance
-Multiple null checks(It doesn't work without them)
-Checks to make sure entities are within loaded chunks
-Actual entity removal
2021-06-10 17:00:09 -04:00
opfromthestart
3879e5ffac Sand Towers Fall
-The listener in TestWorldGenerator updates any block above it if that block is a block that can be affected by gravity.
-Format happened(I forgot)
2021-06-10 15:56:15 -04:00
opfromthestart
47eb9fa5af Conservation of Matter
-Placing a Test:Sand block now deletes the block and summons a Test:FallingBlock in its place.
2021-06-10 14:08:35 -04:00
opfromthestart
bf49687ab6 Better performance maybe?
-Changed as many of the ClientState statements to context as I could.
-Only looks for a sand based update once per block update(I think it was twice before)
2021-06-10 12:50:51 -04:00
opfromthestart
b3ae829383 Almost All Works
-Added Set in TestEntityLogicFallingBlock to keep track of gravity blocks
  -Used this set in listener in TestWorldGenerator
-setInvisible and isDone() methods in TestEntityDataFallingBlock
  -Used to determine if the entity should be rendered/cared about in TestEntityRenderFallingBlock and TestEntityLogicFallingBlock
-Added more accurate Vec3i mod and div methods in TestEntityLogicFallingBlock
  *Change this to a better place
-TestEntityLogicFallingBlock actually places the block when the entity lands
-Better air block detection in TestWorldGenerator
*Still cannot erase the original placed block, not sure why.
2021-05-09 15:57:38 -04:00
opfromthestart
b374e9a736 Added FallingBlock Classes
-Added TestEntityDataFallingBlock class
  -Right now only supports Test:Sand
  -Kinda just copied from Statie
-Added TestEntityRenderFallingBlock
  -Used BlockRenderTexturedCube and TestEntityRenderStatie for this one
  -Has a setTexture method, but it needs improving
-Added TestEntityLogicFallingBlock class
  -Allows for a falling block to return to being a block.
  -The coordinates of the entity never move, even if it does ingame.
-In TestContent
  -Registers Test:FallingBlock
-In TestWorldGenerator
  -Adds listener for a sand block being placed
    -Listener replaces the block with a FallingBlock entity
    -It should also replace the block with air but it hasn't been working for me.
2021-05-04 20:29:06 -04:00
556 changed files with 5198 additions and 12802 deletions

2
.gitattributes vendored
View File

@ -6,4 +6,4 @@
* text=auto eol=lf * text=auto eol=lf
*.bat text eol=crlf *.bat text eol=crlf
*.nsi text eol=crlf

View File

@ -1,49 +0,0 @@
name: Bug Report
description: Let us know about a problem
labels: [bug]
body:
- type: markdown
attributes:
value: |
Use this template to report identified problems. If the game suddenly crashed, and you need help identifying the cause of a crashreport, please use the Investigate Crashreport template instead.
**Do not forget to give your issue a descriptive title.**
- type: textarea
attributes:
label: Steps to reproduce
description: |
What did you do just before the problem appeared, or where can it be observed?
If the issue occurs unreliably, please estimate the probability of the crash.
placeholder: |
1. Look at a cow
2. Wait for the cow to look back
3. The cow turns away after a minute
The issue occurs approximately once every 10 attempts.
Player inventory must be empty. Does not occur in multiplayer. Occurred inside a virtual machine.
validations:
required: true
- type: textarea
attributes:
label: Expected behaviour
description: |
What should happen?
placeholder: |
The cow should stare back indefinitely, because obviously it should, and because comedy.
validations:
required: true
- type: textarea
attributes:
label: Other information
description: What else can you tell us about this bug?
validations:
required: false
- type: textarea
attributes:
label: Crashreport
description: If you have a relevant crashreport, paste the contents of the crashreport file here
render: text
validations:
required: false

View File

@ -1,5 +0,0 @@
blank_issues_enabled: true
contact_links:
- name: Official Progressia Discord
url: https://discord.gg/TWuXbVmX23
about: Ask developers or community members for help

View File

@ -1,41 +0,0 @@
name: Investigate Crashreport
description: Submit a crashreport to determine the problem
labels: [bug, crashreport]
body:
- type: markdown
attributes:
value: |
Use this template to submit crashreports for initial analisys. If you don't have a crashreport, or you have a good understanding of the underlying cause, please use the Bug Report template instead.
Crashreports can be found in `WORKING-DIRECTORY/crashreports` (take notice of the timestamp). `WORKING-DIRECTORY` is `C:\Users\<windows-user>\AppData\Roaming\Progressia` on Windows when using the installer.
**Do not forget to give your issue a descriptive title.**
- type: textarea
attributes:
label: Steps to reproduce
description: |
What did you do just before the crash? How could someone else reproduce it? What other context might be relevant?
If the issue occurs unreliably, please estimate the probability of the crash.
placeholder: |
1. Enter a new world
2. Turn around
3. Wait 5 minutes
4. Game crashes half of the time
Player inventory must be empty. Does not crash in multiplayer. Occurred inside a virtual machine.
validations:
required: true
- type: textarea
attributes:
label: Other information
description: What else can you tell us about this crashreport?
validations:
required: false
- type: textarea
attributes:
label: Crashreport
description: Paste the contents of the crashreport file here
render: text
validations:
required: true

View File

@ -1,31 +1,25 @@
/* /*
* Build logic for Progressia * build.gradle for Progressia
* build.gradle
*
* Please refer to
*
* docs/building/BuildScriptReference.md
*
* for user reference.
*/ */
plugins { plugins {
id 'java' // Apply the java-library plugin to add support for Java Library
id 'java-library'
// GrGit
// A JGit wrapper for Groovy used to access git commit info /*
id 'org.ajoberstar.grgit' version '4.1.1' * Uncomment the following line to enable the Eclipse plugin.
* This is only necessary if you don't use Buildship plugin from the IDE
*/
//id 'eclipse'
} }
/*
* Configure Java version
*/
java { java {
sourceCompatibility = JavaVersion.VERSION_1_8 /*
targetCompatibility = JavaVersion.VERSION_1_8 * We're Java 8 for now.
* Why? As of 2020, most users have Oracle Java, which only supports Java 8.
*/
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
} }
compileJava { compileJava {
@ -35,378 +29,287 @@ compileJava {
* However, on JDK 9 and later versions, '--release' option is required, * However, on JDK 9 and later versions, '--release' option is required,
* which is missing on JDK 8. * which is missing on JDK 8.
*/ */
if (JavaVersion.current() != JavaVersion.VERSION_1_8) { if (JavaVersion.current() != JavaVersion.VERSION_1_8) {
options.compilerArgs.addAll(['--release', '8']) options.compilerArgs.addAll(['--release', '8'])
} }
} }
/*
* Set encoding
*/
compileJava {
options.encoding = 'utf8'
}
/* /*
* Dependencies * Dependencies
*/ */
repositories { repositories {
mavenCentral() mavenCentral()
jcenter()
/*
* Windcorp Maven repository /*
* Currently used by: * Specify Windcorp Maven repository
* - ru.windcorp.fork.io.github.java-graphics:glm:1.0.1 * Currently used by:
*/ * - ru.windcorp.fork.io.github.java-graphics:glm:1.0.1
maven { url 'https://windcorp.ru/./maven' } */
maven { url 'https://windcorp.ru/./maven' }
} }
dependencies { dependencies {
// Google Guava // Google Guava
// A generic utilities library // A generic utilities library
implementation 'com.google.guava:guava:31.0.1-jre' implementation 'com.google.guava:guava:30.0-jre'
// Trove4j // Trove4j
// Provides optimized Collections for primitive types // Provides optimized Collections for primitive types
implementation 'net.sf.trove4j:trove4j:3.0.3' implementation 'net.sf.trove4j:trove4j:3.0.3'
// java-graphics // java-graphics
// A GLM (OpenGL Mathematics) port to Java // A GLM (OpenGL Mathematics) port to Java
// Unfortunately, Maven Central Repository provides an outdated version of this library, which contains several critical bugs // Unfortunately, Maven Central Repository provides an outdated version of this library, which contains several critical bugs
implementation 'ru.windcorp.fork.io.github.java-graphics:glm:1.0.1' implementation 'ru.windcorp.fork.io.github.java-graphics:glm:1.0.1'
// Log4j // Log4j
// A logging library // A logging library
implementation 'org.apache.logging.log4j:log4j-api:2.17.1' implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.13.3'
implementation 'org.apache.logging.log4j:log4j-core:2.17.1' implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.13.3'
// JUnit // JUnit
// A unit-testing library // A unit-testing library
testImplementation 'junit:junit:4.13.2' testImplementation 'junit:junit:4.12'
// Also see LWJGL dependencies in build_logic/lwjgl.gradle // See LWJGL dependencies below
} }
/* /*
* Version resolution * Progressia uses the following LWJGL libraries:
* - Core libraries
* - OpenGL
* - OpenAL
* - GLFW
* - STB
*/ */
import org.ajoberstar.grgit.* /*
* LWJGL
* (auto-generated script)
* ((here be dragons))
*/
// Pattern: vMAJOR.MINOR.PATCH[-SUFFIX] import org.gradle.internal.os.OperatingSystem
project.ext.tagFormat = /^v(\d+)\.(\d+)\.(\d+)(-[\w\-]*)?$/
String version_parseVersion(String tag, boolean increment) { project.ext.lwjglVersion = "3.2.3"
try {
switch (OperatingSystem.current()) {
case OperatingSystem.LINUX:
def osArch = System.getProperty("os.arch")
project.ext.lwjglNatives = osArch.startsWith("arm") || osArch.startsWith("aarch64")
? "natives-linux-${osArch.contains("64") || osArch.startsWith("armv8") ? "arm64" : "arm32"}"
: "natives-linux"
break
case OperatingSystem.MAC_OS:
project.ext.lwjglNatives = "natives-macos"
break
case OperatingSystem.WINDOWS:
project.ext.lwjglNatives = System.getProperty("os.arch").contains("64") ? "natives-windows" : "natives-windows-x86"
break
}
dependencies {
implementation platform("org.lwjgl:lwjgl-bom:$lwjglVersion")
implementation "org.lwjgl:lwjgl"
implementation "org.lwjgl:lwjgl-glfw"
implementation "org.lwjgl:lwjgl-openal"
implementation "org.lwjgl:lwjgl-opengl"
implementation "org.lwjgl:lwjgl-stb"
def data = (tag =~ tagFormat)[0] runtimeOnly "org.lwjgl:lwjgl::$lwjglNatives"
runtimeOnly "org.lwjgl:lwjgl-glfw::$lwjglNatives"
runtimeOnly "org.lwjgl:lwjgl-openal::$lwjglNatives"
runtimeOnly "org.lwjgl:lwjgl-opengl::$lwjglNatives"
runtimeOnly "org.lwjgl:lwjgl-stb::$lwjglNatives"
}
// LWJGL END
/*
* Tasks
*/
/*
* Additional native libraries specification
*/
project.ext.platforms = new HashSet<>()
task addNativeDependencies {
doFirst {
def archs = project.ext.platforms
def major = data[1] switch (archs.size()) {
def minor = data[2] case 0:
def patch = data[3] as int println "Adding LWJGL native dependencies for local platform only:\n\t$lwjglNatives"
def suffix = data[4] ?: '' archs.add project.ext.lwjglNatives
break
if (increment) { case 1:
def oldVersion = "$major.$minor.$patch$suffix" println "Adding LWJGL native dependencies for platform\n\t" + archs.get(0)
patch++ break
def newVersion = "$major.$minor.$patch$suffix" default:
println "Adding LWJGL native dependencies for platforms:\n\t" + archs.join("\n\t")
logger.info "Version parsed from Git: $oldVersion, incremented to $newVersion"
return newVersion
} else {
def newVersion = "$major.$minor.$patch$suffix"
logger.info "Version parsed from Git: $newVersion"
return newVersion
} }
} catch (any) { if (project.ext.lwjglNatives.isEmpty()) println "WTF"
logger.warn "Could not parse version from tag \"$tag\""
return tag dependencies {
archs.each { arch ->
runtimeOnly "org.lwjgl:lwjgl::$arch"
runtimeOnly "org.lwjgl:lwjgl-glfw::$arch"
runtimeOnly "org.lwjgl:lwjgl-openal::$arch"
runtimeOnly "org.lwjgl:lwjgl-opengl::$arch"
runtimeOnly "org.lwjgl:lwjgl-stb::$arch"
}
}
}
}
compileJava.mustRunAfter addNativeDependencies // Make sure runtimeOnly has not been resolved
task requestLinuxDependencies {
description 'Adds linux, linux-arm64 and linux-arm32 native libraries to built artifacts.'
doFirst {
project.ext.platforms.addAll(['natives-linux', 'natives-linux-arm64', 'natives-linux-arm32'])
}
}
task requestWindowsDependencies {
description 'Adds windows and windows-x86 native libraries to built artifacts.'
doFirst {
project.ext.platforms.addAll(['natives-windows', 'natives-windows-x86'])
}
}
task requestMacOSDependencies {
description 'Adds macos native libraries to built artifacts.'
doFirst {
project.ext.platforms.addAll(['natives-macos'])
} }
} }
Tag version_findRelevantTag(Grgit git) { def dependencySpecificationTasks = tasks.findAll { task -> task.name.startsWith('request') && task.name.endsWith('Dependencies') }
def tags = git.tag.list()
task requestCrossPlatformDependencies {
def commits = [ git.head() ] description 'Adds native libraries for all available platforms to built artifacts.'
def visited = new HashSet<>() dependsOn dependencySpecificationTasks
while (true) {
if (commits.isEmpty()) return null
def nextCommits = new HashSet<>()
def formatSpecificationPrinted = false
for (def commit : commits) {
def tag = tags.findAll { it.commit == commit } ?.max { it.dateTime }
if (tag != null) {
if (tag.name ==~ tagFormat) {
return tag
} else {
if (!formatSpecificationPrinted) {
formatSpecificationPrinted = true
logger.info 'Expecting tag format: vMAJOR.MINOR.PATCH[-SUFFIX]'
}
logger.info 'Ignoring tag due to invalid format: {}', tag.name
}
}
nextCommits.addAll commit.parentIds.collect(git.resolve.&toCommit)
}
visited.addAll commits
nextCommits.removeAll visited
commits = nextCommits
}
} }
task resolveVersion { addNativeDependencies.mustRunAfter dependencySpecificationTasks
description 'Resolves version information from Git repository or project properties.'
/*
* Determines if the provided dependency should be packaged
*/
def isDependencyRequested(String dep) {
if (dep.endsWith(".jar")) {
dep = dep.substring(0, dep.length() - ".jar".length())
}
return !dep.contains("natives-") ||
project.ext.platforms.contains(dep.substring(dep.indexOf("natives-"), dep.length()))
}
/*
* Manifest specification
*/
task specifyLocalManifest {
dependsOn addNativeDependencies // Make sure all native dependencies are specified
doFirst { doFirst {
def classPath = []
project.ext.commit = System.env.GIT_COMMIT configurations.runtimeClasspath.each {
project.ext.branch = System.env.GIT_BRANCH if (isDependencyRequested(it.getName())) {
classPath.add("lib/" + it.getName())
try {
def git = Grgit.open(dir: project.projectDir)
project.ext.commit = commit ?: git.head().id
project.ext.branch = branch ?: git.branch.current().name
if (project.version != 'unspecified') {
// Leave version as-is
} else { } else {
println "\tRemoving from JAR classpath (not requested): " + it.getName()
// Resolve version from Git
def tag = version_findRelevantTag(git)
if (tag == null) {
String suffix
if (project.hasProperty('buildId')) {
suffix = project.buildId;
} else {
suffix = java.time.ZonedDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern('yyyy_MM_dd'))
}
project.version = "999.0.0-$suffix"
logger.warn 'Git repository does not contain an applicable tag, using dummy version {}\nSpecify version with -Pversion=1.2.3 or create a Git tag named v1.2.3', project.version
} else {
project.version = version_parseVersion(tag.name, tag.commit != git.head())
}
} }
} catch (org.eclipse.jgit.errors.RepositoryNotFoundException e) {
if (project.version == 'unspecified') project.version = 'dev'
project.ext.commit = commit ?: '-'
project.ext.branch = branch ?: '-'
logger.warn 'No Git repository found in project root, using dummy version {}\nSpecify version with -Pversion=1.2.3 or create a Git tag named v1.2.3', project.version
} }
if (branch.contains '/') { if (classPath.size() == configurations.runtimeClasspath.size()) {
// Strip remote - no one wants that println "Nothing removed from JAR classpath"
project.ext.branch = branch.takeAfter '/'
} }
if (!project.hasProperty('buildId')) { jar {
project.ext.buildId = '-' manifest {
attributes(
"Main-Class": "ru.windcorp.progressia.client.ProgressiaClientMain",
"Class-Path": configurations.runtimeClasspath.collect { "lib/" + it.getName() } .findAll { isDependencyRequested(it) } .join(' ')
)
}
} }
} }
doLast {
}
} }
jar.dependsOn specifyLocalManifest
/* /*
* Apply LWJGL logic * Library export
*/
apply from: 'build_logic/lwjgl.gradle'
/*
* Copy libraries into build/libs/lib directory, next to Progressia.jar
*/
task exportLibs(type: Sync) {
description 'Copies runtime libraries into a subdirectory next to the output JAR.'
jar.dependsOn exportLibs
dependsOn lwjgl_addNativesToRuntimeOnly
// from defined in configureManifest
into 'build/libs/lib'
}
/*
* Configure JAR manifest
*/
task configureManifest {
description 'Populates JAR manifest with Main-Class, Class-Path and version metadata.'
jar.dependsOn configureManifest
dependsOn resolveVersion
dependsOn lwjgl_addNativesToRuntimeOnly
doFirst {
def classPath = project.lwjgl.replaceNativesIn(configurations.runtimeClasspath)
exportLibs.from classPath
jar.manifest.attributes(
'Main-Class': 'ru.windcorp.progressia.client.ProgressiaClientMain',
'Class-Path': classPath.collect { "lib/${java.net.URLEncoder.encode it.name}" } .join(' '),
'Specification-Title': 'Progressia',
'Implementation-Title': 'Progressia',
'Implementation-Version': project.version,
'Implementation-Version-Git-Commit': project.commit,
'Implementation-Version-Git-Branch': project.branch,
'Implementation-Version-BuildId': project.buildId,
)
}
}
/*
* Packaging working directory configuration
*/
import java.nio.file.*
import java.nio.file.attribute.*
task deletePackagingDirs(type: Delete) {
description 'Deletes build/tmp/packaging directory.'
followSymlinks = false
delete 'build/tmp/packaging'
}
task linkBuildOutputForPackaging {
description 'Symlinks the contents of build/libs into packaging working directory.'
dependsOn build
mustRunAfter deletePackagingDirs
onlyIf { preparePackaging.ext.mode == 'symlink' }
ext.from = 'build/libs'
ext.into = "build/tmp/packaging/workingDir/${ -> preparePackaging.ext.buildDest}"
inputs.dir from
outputs.dir into
doLast {
def fromPath = Paths.get from
def intoPath = Paths.get into
Files.createDirectories intoPath
Files.list(fromPath).each {
def fileName = it.fileName.toString()
// Exclude all JARs except the current one
if (fileName ==~ "${project.name}.*\\.jar" && fileName != tasks.jar.archiveFileName.get())
return
Files.createSymbolicLink intoPath.resolve(it.fileName), intoPath.relativize(it)
}
}
}
task copyBuildOutputForPackaging(type: Copy) {
description 'Copies the contents of build/libs into packaging working directory.'
dependsOn build
mustRunAfter deletePackagingDirs
onlyIf { preparePackaging.ext.mode == 'copy' }
from 'build/libs'
filesMatching("${project.name}*.jar") {
include tasks.jar.archiveFileName.get()
}
into "build/tmp/packaging/workingDir/${ -> preparePackaging.ext.buildDest}"
}
task preparePackaging {
preparePackaging.ext.buildDest = ''
preparePackaging.ext.mode = 'symlink'
dependsOn deletePackagingDirs
dependsOn linkBuildOutputForPackaging
dependsOn copyBuildOutputForPackaging
}
/*
* Apply all packaging scripts
*/
new File(projectDir, 'build_logic/packaging').list().each {
apply from: "build_logic/packaging/$it/script.gradle"
}
/*
* Ensure no more than one packaging task is scheduled
*/ */
gradle.taskGraph.whenReady { graph -> task exportLibs(type: Sync) {
if (graph.allTasks.count { it.name ==~ /package[^_]*/ } > 1) { mustRunAfter addNativeDependencies
def offenders = graph.allTasks.findAll { it.name ==~ /package[^_]*/ }
throw new GradleException("Cannot execute multiple package tasks within a single build\n" + into libsDirectory.get().getAsFile().getPath() + "/lib"
"\tOffending tasks: $offenders") exclude { !isDependencyRequested(it.getName()) }
} from configurations.runtimeClasspath
} }
jar.dependsOn(exportLibs)
/* /*
* Convenience build tasks * Packaging
*/ */
task packageDebian(type: Exec) {
description 'Builds the project and creates a Debain package.'
group 'Progressia'
dependsOn build
dependsOn requestLinuxDependencies
commandLine './buildPackages.sh', 'debian'
doLast {
println "Debian package available in build_packages/"
}
}
task packageWindows(type: Exec) {
description 'Builds the project and creates a Windows installer.'
group 'Progressia'
dependsOn build
dependsOn requestWindowsDependencies
commandLine './buildPackages.sh', 'windows'
doLast {
println "Windows installer available in build_packages/"
}
}
task buildCrossPlatform { task buildCrossPlatform {
description 'Builds the project including native libraries for all available platforms.' description 'Builds the project including native libraries for all available platforms.'
group 'Progressia' group 'Progressia'
dependsOn requestCrossPlatformDependencies dependsOn requestCrossPlatformDependencies
dependsOn build dependsOn build
doLast { doLast {
logger.info 'Native libraries for all platforms have been added' println "Native libraries for all platforms have been added"
} }
} }
task buildLocal { task buildLocal {
description "Builds the project including only native libraries for current platform (${lwjgl.localArch})." description "Builds the project including only native libraries for current platform ($lwjglNatives)."
group 'Progressia' group 'Progressia'
dependsOn build dependsOn build
doLast { doLast {
logger.info "Native libraries only for platform ${lwjgl.localArch} have been added" println "Native libraries only for platform $lwjglNatives have been added"
} }
} }

191
buildPackages.sh Executable file
View File

@ -0,0 +1,191 @@
#!/bin/bash
#
# Progressia
# Copyright (C) 2020-2021 Wind Corporation and contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
echoerr() { echo "$@" 1>&2; }
buildDebianPackage() {
# Commands that must be available to execute this action
requiredCommands='dpkg-deb fakeroot'
# Package name. Sync with control file manually!
name='progressia-techdemo'
# Version that the package will receive. Sync with control file manually!
version='1.0_all'
# This directory will be copied into $tmpDir
templateDirectory="build_packages/DEB/template"
# Files that must be present
requiredFiles="$templateDirectory/DEBIAN/control"
nameAndVersion="$name-$version"
tmpDir="build_packages/DEB/$nameAndVersion"
outputFile="build_packages/DEB/$nameAndVersion.deb"
echo "Checking environment to build Debian package"
for item in $requiredCommands; do
if command -v "$item" &> /dev/null; then
echo "- $item found"
else
echoerr "Command $item not found, cannot package"
exit 100
fi
done
for file in $requiredFiles; do
if ! [ -r "$file" ]; then
echoerr "$file is missing or not readable, cannot package"
exit 101
else
echo "- $file is present and readable"
fi
done
echo "Environment OK; packaging Debian package"
exitCode=0
{
shareDir="$tmpDir/usr/share/progressia"
mkdir -p "$tmpDir" &&
mkdir -p "$shareDir" &&
cp -r "$templateDirectory"/* "$tmpDir" &&
cp -r 'build/libs/lib' "$shareDir/lib" &&
cp 'build/libs/Progressia.jar' "$shareDir/Progressia.jar" &&
echo "------ DPKG-DEB ------" &&
fakeroot dpkg-deb --build "$tmpDir" &&
echo "---- DPKG-DEB END ----" &&
mv "$outputFile" build_packages
} || {
echoerr "Could not create Debian package"
exitCode=1
}
{
if [ -d "$tmpDir" ]; then
rm -r "$tmpDir"
fi
echo "Cleaned up"
} || {
echoerr "Could not clean up after packaging Debian package"
exitCode=2
}
exit "$exitCode"
}
buildWindowsInstaller() {
# Commands that must be available to execute this action
requiredCommands='makensis'
# NSIS configuration file that must be present
configurationFile='build_packages/NSIS/ProgressiaInstaller.nsi'
# File that will be output
outputFile='build_packages/NSIS/ProgressiaInstaller.exe'
echo "Checking environment to build Windows installer"
for item in $requiredCommands; do
if command -v "$item" &> /dev/null; then
echo "- $item found"
else
echoerr "Command $item not found, cannot build"
exit 100
fi
done
if ! [ -r "$configurationFile" ]; then
echoerr "$configurationFile is missing or not readable, cannot build"
exit 101
else
echo "- $configurationFile is present and readable"
fi
echo "Environment OK; building Windows installer"
exitCode=0
{
cp -r 'build/libs/lib' 'build_packages/NSIS/lib' &&
cp 'build/libs/Progressia.jar' 'build_packages/NSIS/Progressia.jar' &&
cp 'LICENSE' 'build_packages/NSIS/LICENSE.txt' &&
echo "------ NSIS ------" &&
makensis "$configurationFile" &&
echo "---- NSIS END ----" &&
mv "$outputFile" build_packages
} || {
echoerr "Could not build Windows installer"
exitCode=1
}
{
if [ -d 'build_packages/NSIS/lib' ]; then
rm -r 'build_packages/NSIS/lib'
fi
if [ -e 'build_packages/NSIS/Progressia.jar' ]; then
rm 'build_packages/NSIS/Progressia.jar'
fi
if [ -e 'build_packages/NSIS/LICENSE.txt' ]; then
rm 'build_packages/NSIS/LICENSE.txt'
fi
echo "Cleaned up"
} || {
echoerr "Could not clean up after building Windows installer"
exitCode=2
}
exit "$exitCode"
}
printUsage() {
echoerr "Usage: $0 TARGET"
echoerr " where TARGET is 'debian' or 'windows'"
}
if [ -n "$2" ]; then
echoerr "Too many arguments."
printUsage
exit 202
fi
case "$1" in
"debian")
buildDebianPackage
;;
"windows")
buildWindowsInstaller
;;
"")
echoerr "No action specified"
printUsage
exit 200
;;
"--help" | "-help" | "help" | "?")
printUsage
;;
*)
echoerr "Unknown action '$1'"
printUsage
exit 201
;;
esac

View File

@ -1,149 +0,0 @@
/*
* Build logic for Progressia
* LWJGL dependency logic
*/
project.ext.lwjgl = new HashMap<>()
// Version of LWJGL
lwjgl.version = '3.3.0'
/*
* Target platforms for current operation.
* This is filled in by the request* tasks. This is referenced by the addLwjglNatives task.
* When empty, current platform is assumed.
*/
lwjgl.targets = new HashSet<String>()
// LWJGL components. To include org.lwjgl:lwjgl-foobar, add 'foobar' to this list.
lwjgl.libraries = [
'opengl',
'glfw',
'openal',
'stb'
]
// Determine the architecture of the build environment
import org.gradle.internal.os.OperatingSystem
switch (OperatingSystem.current()) {
case OperatingSystem.LINUX:
def osArch = System.getProperty('os.arch')
lwjgl.localArch = osArch.startsWith('arm') || osArch.startsWith('aarch64')
? "linux-${osArch.contains('64') || osArch.startsWith('armv8') ? 'arm64' : 'arm32'}"
: 'linux'
break
case OperatingSystem.MAC_OS:
lwjgl.localArch = System.getProperty('os.arch').startsWith('aarch64') ? 'macos-arm64' : 'macos'
break
case OperatingSystem.WINDOWS:
def osArch = System.getProperty('os.arch')
lwjgl.localArch = osArch.contains('64')
? "windows${osArch.startsWith('aarch64') ? '-arm64' : ''}"
: 'windows-x86'
break
default:
logger.info "Unknown or unsupported OS type according to Gradle's org.gradle.internal.os.OperatingSystem: ${OperatingSystem.current()}"
break
}
configurations {
create 'lwjglNatives'
}
// Declare pure-Java dependencies
dependencies {
// BOM
def bom = platform("org.lwjgl:lwjgl-bom:${lwjgl.version}")
implementation bom
lwjglNatives bom
// Core
implementation 'org.lwjgl:lwjgl'
// Local natives for core
runtimeOnly "org.lwjgl:lwjgl::natives-${lwjgl.localArch}"
// Components
lwjgl.libraries.each { lib ->
implementation "org.lwjgl:lwjgl-$lib"
// Local natives for component
runtimeOnly "org.lwjgl:lwjgl-$lib::natives-${lwjgl.localArch}"
}
}
/*
* Adds LWJGL native libraries to lwjglNatives configuration
*/
task lwjgl_addNativesToRuntimeOnly {
doFirst {
if (project.hasProperty('forceTargets')) {
try {
def oldTargets = lwjgl.targets.join(',')
lwjgl.targets.clear()
lwjgl.targets.addAll project.forceTargets.split(',')*.trim().collect { it == 'local' ? lwjgl.localArch : it }
logger.info 'Overriding selected platforms {} with {}', oldTargets, lwjgl.targets.join(',')
} catch (Exception e) {
throw new GradleException("Could not parse forceTargets \"${project.forceTargets}\", expecting platform-1,platform-2,local", e)
}
}
if (lwjgl.targets.isEmpty()) {
logger.info 'Adding LWJGL native dependencies for local platform only: {}', lwjgl.localArch
lwjgl.targets.add lwjgl.localArch
} else {
logger.info 'Adding LWJGL native dependencies for platforms: {}', lwjgl.targets.sort().join(', ')
}
if (lwjgl.targets.contains(null)) {
if (lwjgl.localArch != null) {
throw new GradleException("Requested local LWJGL natives; could not determine local architecture for OS ${OperatingSystem.current()} with os.arch ${System.getProperty('os.arch')}")
} else {
throw new GradleException("LWJGL targets resolved to ${lwjgl.targets}")
}
}
dependencies {
lwjgl.targets.each { target ->
lwjglNatives "org.lwjgl:lwjgl::natives-$target"
lwjgl.libraries.each { lib ->
lwjglNatives "org.lwjgl:lwjgl-$lib::natives-$target"
}
}
}
}
}
// Replaces LWJGL natives in the given configuration with the requested ones
lwjgl.replaceNativesIn = { config ->
new ArrayList<File>().tap {
addAll config
removeIf { it.name ==~ /.*lwjgl.*natives.*/ }
addAll project.configurations.lwjglNatives
}
}
task requestCrossPlatformDependencies {
description 'Adds LWJGL natives for all available platforms.'
lwjgl_addNativesToRuntimeOnly.mustRunAfter requestCrossPlatformDependencies
}
def requestTask(String name, String... targets) {
def theTask = task "request${name}Dependencies"
theTask.doFirst {
lwjgl.targets.addAll targets
}
theTask.description "Adds LWJGL natives for $name (${targets.join(', ')})."
requestCrossPlatformDependencies.dependsOn theTask
lwjgl_addNativesToRuntimeOnly.mustRunAfter theTask
}
requestTask 'Linux', 'linux', 'linux-arm32', 'linux-arm64'
requestTask 'Windows', 'windows', 'windows-arm64', 'windows-x86'
requestTask 'MacOS', 'macos', 'macos-arm64'

View File

@ -1,42 +0,0 @@
task packageDeb_processResources(type: Copy) {
dependsOn resolveVersion
dependsOn preparePackaging
from 'src/packaging/deb'
filesMatching('DEBIAN/control') {
expand(version: { -> project.version})
}
into 'build/tmp/packaging/workingDir'
}
task packageDeb_configure() {
preparePackaging.mustRunAfter packageDeb_configure
doLast {
tasks.preparePackaging.ext.buildDest = 'usr/share/progressia'
tasks.preparePackaging.ext.mode = 'copy'
}
}
task packageDeb(type: Exec) {
description 'Builds the project and creates a Debian package.'
group 'Progressia'
dependsOn packageDeb_configure
dependsOn requestLinuxDependencies
dependsOn build
dependsOn preparePackaging
dependsOn packageDeb_processResources
doFirst {
mkdir 'build/packages'
}
executable 'dpkg-deb'
args '--root-owner-group'
args '--build', 'build/tmp/packaging/workingDir'
args 'build/packages'
}

View File

@ -1,54 +0,0 @@
task packageNsis_processResources(type: Copy) {
dependsOn preparePackaging
from ('src/packaging/nsis') {
exclude 'left_side.png'
}
from('LICENSE') {
rename 'LICENSE', 'LICENSE.txt'
}
into 'build/tmp/packaging/workingDir'
}
task packageNsis_generateIcon(type: Exec) {
mustRunAfter preparePackaging
executable 'convert'
args files('src/main/resources/assets/icons/*.original.png').files*.path
args 'build/tmp/packaging/workingDir/logo.ico'
}
task packageNsis_generateLeftSide(type: Exec) {
mustRunAfter preparePackaging
executable 'convert'
args 'src/packaging/nsis/left_side.png'
args '-alpha', 'off'
args 'BMP3:build/tmp/packaging/workingDir/left_side.bmp'
}
task packageNsis(type: Exec) {
description 'Builds the project and creates a Windows NSIS installer.'
group 'Progressia'
dependsOn requestWindowsDependencies
dependsOn build
dependsOn resolveVersion
dependsOn preparePackaging
dependsOn packageNsis_processResources
dependsOn packageNsis_generateIcon
dependsOn packageNsis_generateLeftSide
doFirst {
mkdir 'build/packages'
}
executable 'makensis'
args '-NOCONFIG'
args "-DPROJECT_NAME=${project.name}"
args "-DPROJECT_VERSION=${ -> project.version}"
args "-DMAIN_JAR_FILE=${ -> project.tasks.jar.archiveFileName.get()}"
args "-DOUTPUT_DIR=${project.buildDir.absolutePath}/packages"
args 'build/tmp/packaging/workingDir/config.nsi'
}

View File

@ -1,45 +0,0 @@
task packageZip_processResources(type: Copy) {
dependsOn preparePackaging
from ('src/packaging/zip') {
filesMatching('start.*') {
filter(
org.apache.tools.ant.filters.ReplaceTokens,
tokens: [mainJarFile: project.tasks.jar.archiveFileName.get()]
)
}
}
from ('src/main/resource/assets/icons/logo256.original.png') {
rename 'logo256.original.png', 'logo.png'
}
from('LICENSE') {
rename 'LICENSE', 'LICENSE.txt'
}
into 'build/tmp/packaging/workingDir'
}
task packageZip(type: Zip) {
description 'Builds the project and creates a cross-platform ZIP package.'
group 'Progressia'
dependsOn resolveVersion
dependsOn requestCrossPlatformDependencies
dependsOn build
dependsOn preparePackaging
dependsOn packageZip_processResources
archiveBaseName = project.name
archiveAppendix = 'universal'
doFirst {
archiveVersion = project.version
}
doFirst {
mkdir 'build/packages'
}
from 'build/tmp/packaging/workingDir'
destinationDirectory = file('build/packages')
}

View File

@ -1,8 +1,8 @@
Package: progressia Package: progressia-techdemo
Version: ${version} Version: 1.0
Section: custom Section: custom
Priority: optional Priority: optional
Architecture: all Architecture: all
Maintainer: Javapony <kvadropups@gmail.com> Maintainer: Javapony <kvadropups@gmail.com>
Depends: java8-runtime Depends: java8-runtime
Description: Progressia - a 3D sandbox survival game Description: Progressia Techdemo release

View File

@ -1,164 +1,161 @@
;NSIS Modern User Interface ;NSIS Modern User Interface
;Welcome/Finish Page Example Script ;Welcome/Finish Page Example Script
;Written by Joost Verburg ;Written by Joost Verburg
;-------------------------------- ;--------------------------------
;Include Modern UI ;Include Modern UI
!include "MUI2.nsh" !include "MUI2.nsh"
;-------------------------------- ;--------------------------------
;General ;General
; Expecting the following symbols from caller: !define PROJECT_NAME "Progressia"
; PROJECT_NAME
; PROJECT_VERSION ; MUI Settings / Icons
; MAIN_JAR_FILE !define MUI_ICON "logo.ico"
;!define MUI_UNICON ;Uninstall icon
; MUI Settings / Icons
!define MUI_ICON "logo.ico" ; MUI Settings / Header
;!define MUI_UNICON ;Uninstall icon ; !define MUI_HEADERIMAGE
; !define MUI_HEADERIMAGE_RIGHT
; MUI Settings / Header ; !define MUI_HEADERIMAGE_BITMAP "${NSISDIR}\Contrib\Graphics\Header\orange-r-nsis.bmp"
; !define MUI_HEADERIMAGE ; !define MUI_HEADERIMAGE_UNBITMAP "${NSISDIR}\Contrib\Graphics\Header\orange-uninstall-r-nsis.bmp"
; !define MUI_HEADERIMAGE_RIGHT
; !define MUI_HEADERIMAGE_BITMAP "${NSISDIR}\Contrib\Graphics\Header\orange-r-nsis.bmp" ; MUI Settings / Wizard
; !define MUI_HEADERIMAGE_UNBITMAP "${NSISDIR}\Contrib\Graphics\Header\orange-uninstall-r-nsis.bmp" !define MUI_WELCOMEFINISHPAGE_BITMAP "left_side.bmp"
!define MUI_UNWELCOMEFINISHPAGE_BITMAP "left_side.bmp"
; MUI Settings / Wizard
!define MUI_WELCOMEFINISHPAGE_BITMAP "left_side.bmp" ;Name and file
!define MUI_UNWELCOMEFINISHPAGE_BITMAP "left_side.bmp" Name "${PROJECT_NAME}"
OutFile "${PROJECT_NAME}Installer.exe"
;Name and file Unicode True
Name "${PROJECT_NAME}"
OutFile "${OUTPUT_DIR}/${PROJECT_NAME}-${PROJECT_VERSION}-installer.exe" ;Default installation folder
Unicode True InstallDir "$PROGRAMFILES\${PROJECT_NAME}"
;Default installation folder ;Get installation folder from registry if available
InstallDir "$PROGRAMFILES\${PROJECT_NAME}" InstallDirRegKey HKLM "Software\${PROJECT_NAME}" ""
;Get installation folder from registry if available ;Request application privileges for Windows Vista
InstallDirRegKey HKLM "Software\${PROJECT_NAME}" "" RequestExecutionLevel admin
;Request application privileges for Windows Vista ;--------------------------------
RequestExecutionLevel admin ;Interface Settings
;-------------------------------- !define MUI_ABORTWARNING
;Interface Settings
;--------------------------------
!define MUI_ABORTWARNING ;Pages
;-------------------------------- !insertmacro MUI_PAGE_WELCOME
;Pages !insertmacro MUI_PAGE_LICENSE "LICENSE.txt"
!insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_LICENSE "LICENSE.txt" !insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_COMPONENTS !define MUI_FINISHPAGE_RUN
!insertmacro MUI_PAGE_DIRECTORY !define MUI_FINISHPAGE_RUN_TEXT "Start ${PROJECT_NAME}"
!insertmacro MUI_PAGE_INSTFILES !define MUI_FINISHPAGE_RUN_FUNCTION "LaunchLink"
!define MUI_FINISHPAGE_RUN !insertmacro MUI_PAGE_FINISH
!define MUI_FINISHPAGE_RUN_TEXT "Start ${PROJECT_NAME}"
!define MUI_FINISHPAGE_RUN_FUNCTION "LaunchLink" !insertmacro MUI_UNPAGE_WELCOME
!insertmacro MUI_PAGE_FINISH !insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_COMPONENTS
!insertmacro MUI_UNPAGE_WELCOME !insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_FINISH
!insertmacro MUI_UNPAGE_COMPONENTS
!insertmacro MUI_UNPAGE_INSTFILES ;--------------------------------
!insertmacro MUI_UNPAGE_FINISH ;Languages
;-------------------------------- !insertmacro MUI_LANGUAGE "English"
;Languages
;--------------------------------
!insertmacro MUI_LANGUAGE "English" ;Installer Sections
;-------------------------------- Section "Install ${PROJECT_NAME}" SEC0000
;Installer Sections
SectionIn RO ;Make it read-only
Section "Install ${PROJECT_NAME}" SEC0000 SetOutPath "$INSTDIR"
SetOverwrite on
SectionIn RO ;Make it read-only
SetOutPath "$INSTDIR" ;Files
SetOverwrite on File Progressia.jar
File logo.ico
;Files File /r lib
File "${MAIN_JAR_FILE}"
File logo.ico ;Store installation folder
File /r lib WriteRegStr HKLM SOFTWARE\Progressia "Install_Dir" "$INSTDIR"
;Store installation folder ;Create uninstaller
WriteRegStr HKLM "SOFTWARE\${PROJECT_NAME}" "Install_Dir" "$INSTDIR"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PROJECT_NAME}" "DisplayName" "${PROJECT_NAME} (remove only)"
;Create uninstaller WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PROJECT_NAME}" "UninstallString" "$INSTDIR\Uninstall.exe"
WriteUninstaller "$INSTDIR\Uninstall.exe"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PROJECT_NAME}" "DisplayName" "${PROJECT_NAME} (remove only)"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PROJECT_NAME}" "UninstallString" "$INSTDIR\Uninstall.exe" SectionEnd
WriteUninstaller "$INSTDIR\Uninstall.exe"
Section "Create Desktop Shortcut" SEC0001
SectionEnd SetOutPath "$APPDATA\${PROJECT_NAME}"
CreateShortCut "$DESKTOP\${PROJECT_NAME}.lnk" "$INSTDIR\${PROJECT_NAME}.jar" "" "$INSTDIR\logo.ico"
Section "Create Desktop Shortcut" SEC0001 SectionEnd
SetOutPath "$APPDATA\${PROJECT_NAME}"
CreateShortCut "$DESKTOP\${PROJECT_NAME}.lnk" "$INSTDIR\${MAIN_JAR_FILE}" "" "$INSTDIR\logo.ico" Section "Start Menu Shortcuts" SEC0002
SectionEnd
CreateDirectory "$SMPROGRAMS\${PROJECT_NAME}"
Section "Start Menu Shortcuts" SEC0002 CreateShortcut "$SMPROGRAMS\${PROJECT_NAME}\Uninstall.lnk" "$INSTDIR\Uninstall.exe"
CreateShortcut "$SMPROGRAMS\${PROJECT_NAME}\${PROJECT_NAME}.lnk" "$INSTDIR\${PROJECT_NAME}.jar" "" "$INSTDIR\logo.ico"
CreateDirectory "$SMPROGRAMS\${PROJECT_NAME}"
CreateShortcut "$SMPROGRAMS\${PROJECT_NAME}\Uninstall.lnk" "$INSTDIR\Uninstall.exe" SectionEnd
CreateShortcut "$SMPROGRAMS\${PROJECT_NAME}\${PROJECT_NAME}.lnk" "$INSTDIR\${MAIN_JAR_FILE}" "" "$INSTDIR\logo.ico"
;--------------------------------
SectionEnd ;Uninstaller Section
;-------------------------------- Section "Uninstall"
;Uninstaller Section
;ADD YOUR OWN FILES HERE...
Section "Uninstall"
Delete $INSTDIR\Uninstall.exe
;ADD YOUR OWN FILES HERE... Delete $INSTDIR\Progressia.jar
Delete $INSTDIR\lib\*.*
Delete $INSTDIR\Uninstall.exe Delete $INSTDIR\logo.ico
Delete "$INSTDIR\${MAIN_JAR_FILE}"
Delete $INSTDIR\lib\*.* RMDir $INSTDIR\lib
Delete $INSTDIR\logo.ico
Delete $DESKTOP\${PROJECT_NAME}.lnk
RMDir $INSTDIR\lib
Delete $SMPROGRAMS\${PROJECT_NAME}\Uninstall.lnk
Delete $DESKTOP\${PROJECT_NAME}.lnk Delete $SMPROGRAMS\${PROJECT_NAME}\${PROJECT_NAME}.lnk
Delete $SMPROGRAMS\${PROJECT_NAME}\Uninstall.lnk RMDir $INSTDIR
Delete $SMPROGRAMS\${PROJECT_NAME}\${PROJECT_NAME}.lnk
RMDir /r $SMPROGRAMS\${PROJECT_NAME}
RMDir $INSTDIR
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PROJECT_NAME}"
RMDir /r $SMPROGRAMS\${PROJECT_NAME} DeleteRegKey HKLM "Software\${PROJECT_NAME}"
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PROJECT_NAME}" SectionEnd
DeleteRegKey HKLM "Software\${PROJECT_NAME}"
Section "un.Remove user data"
SectionEnd
RMDir /r "$APPDATA\${PROJECT_NAME}"
Section "un.Remove user data"
SectionEnd
RMDir /r "$APPDATA\${PROJECT_NAME}"
;--------------------------------
SectionEnd ;Functions
;-------------------------------- Function LaunchLink
;Functions SetOutPath "$APPDATA\${PROJECT_NAME}"
ExecShell "" "$INSTDIR\${PROJECT_NAME}.jar"
Function LaunchLink FunctionEnd
SetOutPath "$APPDATA\${PROJECT_NAME}"
ExecShell "" "$INSTDIR\${MAIN_JAR_FILE}" ;--------------------------------
FunctionEnd ;Descriptions
;-------------------------------- ;Language strings
;Descriptions LangString DESC_SecDummy ${LANG_ENGLISH} "Install ${PROJECT_NAME}."
;Language strings ;Assign language strings to sections
LangString DESC_SecDummy ${LANG_ENGLISH} "Install ${PROJECT_NAME}." !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
!insertmacro MUI_DESCRIPTION_TEXT ${SEC0000} $(DESC_SecDummy)
;Assign language strings to sections !insertmacro MUI_FUNCTION_DESCRIPTION_END
!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
!insertmacro MUI_DESCRIPTION_TEXT ${SEC0000} $(DESC_SecDummy)
!insertmacro MUI_FUNCTION_DESCRIPTION_END

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 187 KiB

View File

@ -1,12 +0,0 @@
# Progressia Region File
## Description
The `.progressia_region` file type is used for all region files in the game Progressia. Each region file contains a cube of 16x16x16 chunks.
## Header
The header of the file is 16&nbsp;400 bytes. Every file starts with the string byte sequence `\x50\x52\x4F\x47` (UTF-8 for `PROG`), followed with the three integer values of the region position, in region coordinates. After this, there is exactly 16KiB of space in the header, which stores the offsets to the chunks' data. This space holds an integer, 4 bytes, for each chunk in the region. The integer value starts at 0 for every chunk, and is changed to the location of the chunk data once created. These are indexed in order by flattening the 3D in-chunk coordinates into a number between 0 and 4095 according to the formula `offset = 256*x+ 16*y + z` for chunk at (x, y, z). To convert from this offset value to the offset in bytes, use `byte_offset = 16400 + 64*n`.
## Sectors
Sectors are what is used to store chunk data, and are not linear, but are followed until they reach an ending block. Each is 64 bytes, which is used in the header section to find the byte offset. Each sector starts with a identification byte, followed by the sector data.
0. Ending - This sector is empty, and marks the end of the chunk data (This may change in the future.
1. Data - This sector contains chunk data for a single chunk. The second byte of this sector contains a counter byte, which is a form of "checksum" to make sure that the program is reading the proper sectors in order. This starts at 0 for the first data sector and increments by one for each new data sector.
2. Partition Link - This sector only contains another offset value, which is where the next sector is. This allows for infinite chunk size, avoiding "chunk dupes" as were present in Minecraft without reverting any chunks.
3. Bulk Data - These would be used for many chunks in the same region that contain exactly the same data, e.g. all solid chunks underground. Exists so the program knows not to overwrite them, and just make new chunk data if modified. Not yet implemented.

View File

@ -1,10 +1,8 @@
# Build Guide # Build Guide
This document is a guide to building Progressia from source. For quick reference, see This document is a guide to building Progressia from source.
[Build Script Reference](BuildScriptReference.md).
Compilation should be possible on all platforms that support JDK 8 or later, however, packaging scripts require Compilation should be possible on all platforms that support JDK 8 or later, however, packaging scripts require Bash.
additional programs in `PATH`.
This guide assumes you are familiar with using a terminal or Windows Command Prompt or PowerShell. This guide assumes you are familiar with using a terminal or Windows Command Prompt or PowerShell.
@ -143,8 +141,8 @@ build.
Some users might find the need to build for a specific set of platforms. Inclusion of GNU/Linux, Windows or MacOS Some users might find the need to build for a specific set of platforms. Inclusion of GNU/Linux, Windows or MacOS
dependencies individually can be controlled with the following arguments to the `./gradlew build` command: dependencies individually can be controlled with the following arguments to the `./gradlew build` command:
- `requestLinuxDependencies` requests that `natives-linux`, `natives-linux-arm32` and `natives-linux-arm64` binaries are included; - `requestLinuxDependencies` requests that `natives-linux`, `natives-linux-arm32` and `natives-linux-arm64` binaries are included;
- `requestWindowsDependencies` requests that `natives-windows`, `natives-windows-arm64` and `natives-windows-x86` binaries are included; - `requestWindowsDependencies` requests that `natives-windows` and `natives-windows-x86` binaries are included;
- `requestMacOSDependencies` requests that `natives-macos`, `natives-macos-arm64` binaries are included. - `requestMacOSDependencies` requests that `natives-macos` binaries are included.
These requests can be applied in any combination. For example, the following command produces a build containing only These requests can be applied in any combination. For example, the following command produces a build containing only
GNU/Linux and Windows natives: GNU/Linux and Windows natives:
@ -152,46 +150,54 @@ GNU/Linux and Windows natives:
./gradlew build requestLinuxDependencies requestWindowsDependencies ./gradlew build requestLinuxDependencies requestWindowsDependencies
``` ```
For finer control please edit `build.gradle` manually by adding the desired natives to the `project.ext.platforms` set like so:
```
project.ext.platforms = new HashSet<>()
project.ext.platforms.add 'natives-windows-x86'
```
## Packaging ## Packaging
A universal ZIP distribution, a Debian package and a Windows NSIS installer may be created automatically by the build A Debian package and a Windows installer can be created automatically on systems that support Bash. These tasks are delegated
script. by Gradle to `buildPackages.sh` in repository root. This script checks the environment and assembles the requested output; the
resulting files are moved into `build_packages`.
### Creating a universal ZIP package
A universal cross-platform ZIP archive can be created with the following Gradle task:
```
./gradlew packageZip
```
Gradle will then build all artifacts necessary to run the game on all available platforms and package game files,
libraries, launch scripts, etc. into a compressed ZIP archive.
The resulting file can be found in `build/packages/`
### Creating a Debian package ### Creating a Debian package
A Debian package can be created with the following Gradle task: A Debian package can be created with the following Gradle task:
``` ```
./gradlew packageDeb ./gradlew packageDebian
``` ```
Gradle will then build all artifacts necessary to run the game on GNU/Linux (all three architectures) and invoke Gradle will then build all artifacts necessary to run the game on GNU/Linux (all three architectures) and invoke
`dpkg-deb`. Commands `dpkg-deb` must be available in system path in order to build the package. `./buildPackages.sh debian`. Commands `dpkg-deb` and `fakeroot` must be available in system path in order to build the package.
### Creating a Windows installer ### Creating a Windows installer
A Windows NSIS installer can be created with the following Gradle task: A Windows installer can be created with the following Gradle task:
``` ```
./gradlew packageNsis ./gradlew packageWindows
``` ```
Gradle will then build all artifacts necessary to run the game on Windows (both x64 and x86 architectures) and invoke Gradle will then build all artifacts necessary to run the game on Windows (both x64 and x86 architectures) and invoke
`makensis`. `./buildPackages.sh windows`.
Windows installers are implemented with [NSIS](https://nsis.sourceforge.io/). [ImageMagick](https://imagemagick.org), Windows installers are implemented with [NSIS](https://nsis.sourceforge.io/). Command `makensis` must be available in system
a command-line image editing tool, is used to generate some assets for the installer. Commands `makensis` and path in order to build the installer.
`convert` (from ImageMagick) must be available in system path in order to build the installer.
## Gradle tasks summary
- `buildLocal` creates a build optimized for current platform. Use this to quickly build the game during development.
- `buildCrossPlatform` creates a build that supports all known architectures. Use this to build a universal version of the game.
- `build` currently a synonym of `buildLocal`; creates a default build.
- `packageDebian` creates a Debian package. Do not invoke together with `packageWindows`.
- `packageWindows` creates a Windows installer. Do not invoke together with `packageDebian`.
- `requestLinuxDependencies` requests that `natives-linux`, `natives-linux-arm32` and `natives-linux-arm64` binaries are included when building.
- `requestWindowsDependencies` requests that `natives-windows` and `natives-windows-x86` binaries are included when building.
- `requestMacOSDependencies` requests that `natives-macos` binaries are included when building.
- `requestCrossPlatformDependencies` requests that all binaries are included when building.
All other basic and Java-related Gradle tasks are available as well.

View File

@ -1,112 +0,0 @@
# Build Script Reference
This document is a user's reference for the build script of Progressia. For a beginner-friendly guide, see
[Build Guide](BuildGuide.md).
## Gradle tasks summary
- `buildLocal` creates a build optimized for current platform. Use this to quickly build the game during development.
- `buildCrossPlatform` creates a build that supports all known architectures. Use this to build a universal version of the game.
- `build` currently a synonym of `buildLocal`; creates a default build.
- `packageZip` creates a universal ZIP. Incompatible with other `package` tasks.
- `packageDeb` creates a Debian package. Incompatible with other `package` tasks.
- `packageNsis` creates a Windows NSIS installer. Incompatible with other `package` tasks.
- `requestLinuxDependencies` requests that `natives-linux`, `natives-linux-arm32` and `natives-linux-arm64` binaries are included when building.
- `requestWindowsDependencies` requests that `natives-windows`, `natives-windows-arm64` and `natives-windows-x86` binaries are included when building.
- `requestMacOSDependencies` requests that `natives-macos` and `natives-macos-arm64` binaries are included when building.
- `requestCrossPlatformDependencies` requests that all binaries are included when building.
To execute a task, run `./gradlew <task-name>`.
`build`-type tasks output the executable JAR and all libraries required at runtime into `build/libs`. `package`-type
tasks output packages into `build/packages`.
## Packaging tasks
Some packaging tasks require additional software in `PATH`.
| Task | Commands required in `PATH` |
|---------------|------------------------------------------|
| `packageDeb` | `dpkg-deb` |
| `packageZip` | _none_ |
| `packageNsis` | `makensis`, `convert` (from ImageMagick) |
## Version and metadata
### Version scheme
Progressia builds are identified by four parameters: version, Git commit, Git branch and build ID.
Versions roughly follow [semantic versioning](https://semver.org/spec/v2.0.0.html), with each version fitting the
`MAJOR.MINOR.PATCH[-SUFFIX]` pattern. Depending on the build environment (see below), version is either "real" with
no metadata (e.g. `0.43.2` or `1.2.1-beta`) or a dummy fallback with build metadata (e.g. `999.0.0-2021_07_23` or
`999.0.0-WJ3`).
### Version detection
Build script considers three scenarios when determining the version:
1. `version` project property is set explicitly. This may be done in a variety of ways, for example with command line
argument `-Pversion=1.2.3`
(see [Gradle docs](https://docs.gradle.org/current/userguide/build_environment.html#sec:project_properties))
2. Local Git repository is found, and HEAD is tagged appropriately: version is the tag name with leading `v`
stripped. Example: `v1.2.3` is version `1.2.3`
3. Local Git repository is found, and some ancestor of HEAD is tagged appropriately: version is the tag name with
leading `v` stripped and PATCH incremented by one. Example: `v1.2.3` is version `1.2.4`
Tags not named like `vMAJOR.MINOR.PATCH[-SUFFIX]` are ignored for cases 2 and 3.
In all other cases, a fallback dummy value is used for version, appended with build ID or current date.
### Git metadata
Git commit is determined from `GIT_COMMIT` environment variable if it exists, or the state of the local Git
repository, if any, or `-`.
Git branch is determined from `GIT_BRANCH` environment variable if it exists, or the state of the local Git
repository, if any, or `-`.
The names of the environment variables are picked to assist Jenkins builds.
### Build ID
Build ID uniquely identifies artifacts produced by automated build systems. Build ID must be provided explicitly; it
is `-` unless specified otherwise.
The proposed scheme for naming build IDs is `<builder><build-system><build attempt no.>`. For example, builds
executed by WindCorp Jenkins suite have build IDs like `WJ3` or `WJ142`.
Build ID may be set with `buildId` project property. This may be done in a variety of ways, for example with command
line argument `-PbuildId=WJ3`
(see [Gradle docs](https://docs.gradle.org/current/userguide/build_environment.html#sec:project_properties)).
## Native libraries
LWJGL uses native libraries. Build script declares platform-specific dependencies based on the set of target
platforms, `project.ext.lwjgl.targets` (aka `lwjgl.targets`). These dependencies are added to `runtimeOnly`
configuration.
When this set is empty, the script selects natives for current platform. Otherwise, all platforms in the set are
included.
`lwjgl.targets` is populated automatically by packaging tasks and by `buildCrossPlatform`. To add extra targets,
``requestXxxDependencies` tasks may be used.
Target selection mechanism may be overridden with `forceTargets` project property. This may be done in a variety of
ways, for example with command line argument `-PforceTargets=windows-x86,local`
(see [Gradle docs](https://docs.gradle.org/current/userguide/build_environment.html#sec:project_properties)). The
value is a comma-separated list of target architectures. `local` target will be replaced with the automatically
detected current architecture.
### Available targets
| Name | Task |
|-----------------|------------------------------|
| `linux` | `requestLinuxDependencies` |
| `linux-arm32` | `requestLinuxDependencies` |
| `linux-arm64` | `requestLinuxDependencies` |
| `windows` | `requestWindowsDependencies` |
| `windows-arm64` | `requestWindowsDependencies` |
| `windows-x86` | `requestWindowsDependencies` |
| `macos` | `requestMacOSDependencies` |
| `macos-arm64` | `requestMacOSDependencies` |

View File

@ -41,17 +41,4 @@ Run configurations are used by Intellij IDEA to specify how a project must be ru
8. Append `\run` to the 'Working directory' field. Alternatively, specify another location outside of the project's root directory. 8. Append `\run` to the 'Working directory' field. Alternatively, specify another location outside of the project's root directory.
9. Click 'Apply' to save changes. 9. Click 'Apply' to save changes.
Step 8 is required to specify that the game must run in some directory other than the project root, which is the default in Intellij IDEA. Step 8 is required to specify that the game must run in some directory other than the project root, which is the default in Intellij IDEA.
### Applying formatting templates
Windcorp's Progressia repository is formatted with a style defined for Eclipse IDE (sic) in
`templates_and_presets/eclipse_ide`.
Please apply these templates to the project to automatically format the source in a similar fashion.
1. In project context menu, click 'File->Properties'. (`Ctrl+Alt+S`)
2. In 'Editor' > 'Code Style' > 'Java', press gear icon, then click 'Import Scheme' > 'Eclipse code style'
3. In Scheme select 'Project'
4. Open the file `templates_and_presets/eclipse_ide/FormatterProfile.xml` in 'Select Path'.
5. Inside 'Import Scheme' widow click 'Current Scheme' check box after press OK

Binary file not shown.

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-6.0-bin.zip
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

259
gradlew vendored
View File

@ -1,7 +1,7 @@
#!/bin/sh #!/usr/bin/env sh
# #
# Copyright © 2015-2021 the original authors. # Copyright 2015 the original author or authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@ -17,113 +17,78 @@
# #
############################################################################## ##############################################################################
# ##
# Gradle start up script for POSIX generated by Gradle. ## Gradle start up script for UN*X
# ##
# 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 # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
app_path=$0 PRG="$0"
# Need this for relative symlinks.
# Need this for daisy-chained symlinks. while [ -h "$PRG" ] ; do
while ls=`ls -ld "$PRG"`
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path link=`expr "$ls" : '.*-> \(.*\)$'`
[ -h "$app_path" ] if expr "$link" : '/.*' > /dev/null; then
do PRG="$link"
ls=$( ls -ld "$app_path" ) else
link=${ls#*' -> '} PRG=`dirname "$PRG"`"/$link"
case $link in #( fi
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # 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"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD="maximum"
warn () { warn () {
echo "$*" echo "$*"
} >&2 }
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} >&2 }
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "$( uname )" in #( case "`uname`" in
CYGWIN* ) cygwin=true ;; #( CYGWIN* )
Darwin* ) darwin=true ;; #( cygwin=true
MSYS* | MINGW* ) msys=true ;; #( ;;
NONSTOP* ) nonstop=true ;; Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java JAVACMD="$JAVA_HOME/jre/sh/java"
else else
JAVACMD=$JAVA_HOME/bin/java JAVACMD="$JAVA_HOME/bin/java"
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@ -132,7 +97,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD=java 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. 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 Please set the JAVA_HOME variable in your environment to match the
@ -140,95 +105,79 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
case $MAX_FD in #( MAX_FD_LIMIT=`ulimit -H -n`
max*) if [ $? -eq 0 ] ; then
MAX_FD=$( ulimit -H -n ) || if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
warn "Could not query maximum file descriptor limit" MAX_FD="$MAX_FD_LIMIT"
esac fi
case $MAX_FD in #( ulimit -n $MAX_FD
'' | soft) :;; #( if [ $? -ne 0 ] ; then
*) warn "Could not set maximum file descriptor limit: $MAX_FD"
ulimit -n "$MAX_FD" || fi
warn "Could not set maximum file descriptor limit to $MAX_FD" else
esac warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi fi
# Collect all arguments for the java command, stacking in reverse order: # For Darwin, add options to specify how the application appears in the dock
# * args from the command line if $darwin; then
# * the main class name GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
# * -classpath fi
# * -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 # For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
JAVACMD=$( cygpath --unix "$JAVACMD" ) # We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
# Now convert the arguments - kludge to limit ourselves to /bin/sh SEP=""
for arg do for dir in $ROOTDIRSRAW ; do
if ROOTDIRS="$ROOTDIRS$SEP$dir"
case $arg in #( SEP="|"
-*) 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 done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi fi
# Collect all arguments for the java command; # Escape application args
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of save () {
# shell script including quotes and variable substitutions, so put them in for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
# double quotes to make sure that they get re-expanded; and echo " "
# * put everything else in single quotes, so that it's not re-expanded. }
APP_ARGS=`save "$@"`
set -- \ # Collect all arguments for the java command, following the shell quoting and substitution rules
"-Dorg.gradle.appname=$APP_BASE_NAME" \ eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
-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" "$@" exec "$JAVACMD" "$@"

25
gradlew.bat vendored
View File

@ -29,9 +29,6 @@ if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% 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. @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" set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@ -40,7 +37,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if "%ERRORLEVEL%" == "0" goto init
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@ -54,7 +51,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto init
echo. echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@ -64,14 +61,28 @@ echo location of your Java installation.
goto fail goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell

File diff suppressed because it is too large Load Diff

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil; package ru.windcorp.jputil;
import java.lang.reflect.Array; import java.lang.reflect.Array;
@ -611,8 +611,7 @@ public class ArrayUtil {
int end = offset + length; int end = offset + length;
if (end > arrayLength || offset < 0) if (end > arrayLength || offset < 0)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Array contains [0; " + arrayLength + "), requested [" + offset + "; " + end + ")" "Array contains [0; " + arrayLength + "), requested [" + offset + "; " + end + ")");
);
return length; return length;
} }
@ -628,8 +627,7 @@ public class ArrayUtil {
if (end > arrayLength || start < 0) if (end > arrayLength || start < 0)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Array contains [0; " + arrayLength + "), requested [" + start + "; " + end + ")" "Array contains [0; " + arrayLength + "), requested [" + start + "; " + end + ")");
);
return end; return end;
} }

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil; package ru.windcorp.jputil;
import java.io.OutputStream; import java.io.OutputStream;

View File

@ -1,45 +0,0 @@
/*
* JPUtil
* Copyright (C) 2019-2021 OLEGSHA/Javapony and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ru.windcorp.jputil;
public class ConstantsMapException extends RuntimeException {
private static final long serialVersionUID = -4298704891780063127L;
public ConstantsMapException() {
}
public ConstantsMapException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public ConstantsMapException(String message, Throwable cause) {
super(message, cause);
}
public ConstantsMapException(String message) {
super(message);
}
public ConstantsMapException(Throwable cause) {
super(cause);
}
}

View File

@ -1,307 +0,0 @@
/*
* JPUtil
* Copyright (C) 2019-2022 OLEGSHA/Javapony and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ru.windcorp.jputil;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class IntConstantsMap {
private final Map<Integer, String> namesByValue;
private final Map<String, Integer> valuesByName;
protected IntConstantsMap(Map<Integer, String> namesByValue, Map<String, Integer> valuesByName) {
this.namesByValue = namesByValue;
this.valuesByName = valuesByName;
}
public int getValue(String name) {
Integer value = valuesByName.get(name);
if (value == null) {
throw new NoSuchElementException("No constant with name " + name);
}
return value.intValue();
}
public boolean hasConstant(String name) {
return valuesByName.containsKey(name);
}
public String getName(int value) {
String name = namesByValue.get(value);
if (name == null) {
throw new NoSuchElementException("No constant with value " + value);
}
return name;
}
public boolean hasConstant(int value) {
return namesByValue.containsKey(value);
}
public Map<String, Integer> getAll() {
return valuesByName;
}
@Override
public String toString() {
return valuesByName.toString();
}
public static Builder from(Class<?> clazz) {
return new Builder(clazz);
}
public static class Builder {
@FunctionalInterface
public static interface Filter {
boolean test(String name, int value);
}
public class ConstantSpec {
public String name;
public int value;
public void drop() {
if (!extra.contains(name)) {
name = null;
}
}
}
private final List<Consumer<ConstantSpec>> transforms = new ArrayList<>();
private final Set<String> extra = new HashSet<>();
private final Class<?> source;
public Builder(Class<?> source) {
this.source = source;
}
public Builder apply(Consumer<ConstantSpec> transform) {
transforms.add(transform);
return this;
}
public Builder only(Filter filter) {
return apply(s -> {
if (!filter.test(s.name, s.value)) {
s.drop();
}
});
}
public Builder only(Predicate<String> nameFilter) {
return apply(s -> {
if (!nameFilter.test(s.name)) {
s.drop();
}
});
}
public Builder onlyValued(IntPredicate valueFilter) {
return apply(s -> {
if (!valueFilter.test(s.value)) {
s.drop();
}
});
}
public Builder regex(String regex) {
return only(Pattern.compile(regex).asPredicate());
}
public Builder prefix(String prefix) {
return only(n -> n.startsWith(prefix) && n.length() > prefix.length());
}
public Builder exclude(Filter filter) {
return only((n, v) -> !filter.test(n, v));
}
public Builder exclude(Predicate<String> nameFilter) {
return only(nameFilter.negate());
}
public Builder exclude(String... names) {
Set<String> excluded = new HashSet<>();
for (String name : names) {
excluded.add(name);
}
return exclude(excluded::contains);
}
public Builder excludeRegex(String... nameRegexes) {
List<Predicate<String>> tests = new ArrayList<>();
for (String regex : nameRegexes) {
tests.add(Pattern.compile(regex).asPredicate());
}
return only((n, v) -> {
for (Predicate<String> test : tests) {
if (test.test(n)) {
return false;
}
}
return true;
});
}
public Builder extra(String... names) {
for (String name : names) {
extra.add(name);
}
return this;
}
public Builder rename(Function<String, String> renamer) {
apply(s -> {
s.name = renamer.apply(s.name);
});
return this;
}
public Builder stripPrefix(String prefix) {
return apply(s -> {
if (s.name.startsWith(prefix)) {
s.name = s.name.substring(prefix.length());
} else if (extra.contains(s.name)) {
return;
} else {
s.drop();
}
});
}
public IntConstantsMap scan() {
return build(true);
}
public IntConstantsMap scanAll() {
return build(false);
}
private IntConstantsMap build(boolean onlyPublic) {
Map<Integer, String> namesByValue = new HashMap<>();
Map<String, Integer> valuesByName = new HashMap<>();
BiConsumer<String, Integer> putter = (name, value) -> {
if (namesByValue.containsKey(value)) {
throw newDuplicateException("value", value, name, namesByValue.get(value));
}
if (valuesByName.containsKey(name)) {
throw newDuplicateException("name", name, value, valuesByName.get(name));
}
namesByValue.put(value, name);
valuesByName.put(name, value);
};
try {
for (Field field : source.getDeclaredFields()) {
processField(field, putter, onlyPublic);
}
} catch (IllegalAccessException e) {
throw new ConstantsMapException(e);
}
return new IntConstantsMap(
Collections.unmodifiableMap(namesByValue),
Collections.unmodifiableMap(valuesByName)
);
}
private void processField(Field field, BiConsumer<String, Integer> putter, boolean onlyPublic)
throws IllegalAccessException {
if (!Modifier.isStatic(field.getModifiers())) {
return;
}
if (!Modifier.isFinal(field.getModifiers())) {
return;
}
boolean clearAccessible = false;
if (!Modifier.isPublic(field.getModifiers())) {
if (onlyPublic) {
return;
} else if (!isAccessibleFlagSet(field)) {
field.setAccessible(true);
clearAccessible = true;
}
}
try {
ConstantSpec spec = new ConstantSpec();
spec.name = field.getName();
spec.value = field.getInt(null);
for (Consumer<ConstantSpec> t : transforms) {
t.accept(spec);
if (spec.name == null) {
return;
}
}
putter.accept(spec.name, spec.value);
} finally {
if (clearAccessible) {
field.setAccessible(false);
}
}
}
/*
* Yes, this method exists only so that neither Java 8 nor Java 9 complain about deprecation.
*/
@Deprecated
private boolean isAccessibleFlagSet(Field f) {
return f.isAccessible();
}
private ConstantsMapException newDuplicateException(String what, Object common, Object current, Object old) {
return new ConstantsMapException(
String.format(
"Duplicate %1$s: %2$s -> %3$s and %2$s -> %4$s",
what,
common,
current,
old
)
);
}
}
}

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil; package ru.windcorp.jputil;
import java.util.HashMap; import java.util.HashMap;
@ -30,18 +30,8 @@ public class PrimitiveUtil {
private static final Map<Class<?>, Object> PRIMITIVE_TO_NULL = new HashMap<>(); private static final Map<Class<?>, Object> PRIMITIVE_TO_NULL = new HashMap<>();
static { static {
for ( for (Class<?> boxed : new Class<?>[] { Boolean.class, Byte.class, Short.class, Character.class, Integer.class,
Class<?> boxed : new Class<?>[] { Long.class, Float.class, Double.class }) {
Boolean.class,
Byte.class,
Short.class,
Character.class,
Integer.class,
Long.class,
Float.class,
Double.class
}
) {
try { try {
PRIMITIVE_TO_BOXED.put((Class<?>) boxed.getField("TYPE").get(null), boxed); PRIMITIVE_TO_BOXED.put((Class<?>) boxed.getField("TYPE").get(null), boxed);
} catch (Exception e) { } catch (Exception e) {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil; package ru.windcorp.jputil;
import java.util.function.*; import java.util.function.*;
@ -40,8 +40,7 @@ import java.util.stream.Stream;
/** /**
* Contains static methods to create {@link Stream Streams} that synchronize * Contains static methods to create {@link Stream Streams} that synchronize
* their * their <a href=
* <a href=
* "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps"> * "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps">
* terminal operations</a> on a given monitor. * terminal operations</a> on a given monitor.
* *
@ -50,7 +49,7 @@ import java.util.stream.Stream;
*/ */
// SonarLint: "Stream.peek" should be used with caution (java:S3864) // SonarLint: "Stream.peek" should be used with caution (java:S3864)
// We are implementing Stream, so peek() is required. // We are implementing Stream, so peek() is required.
@SuppressWarnings("squid:S3864") @SuppressWarnings("squid:S3864")
public class SyncStreams { public class SyncStreams {
@ -1070,21 +1069,18 @@ public class SyncStreams {
} }
/** /**
* Wraps the given {@link Stream} to make all * Wraps the given {@link Stream} to make all <a href=
* <a href=
* "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps"> * "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps">
* terminal operations</a> acquire the provided monitor's lock before * terminal operations</a> acquire the provided monitor's lock before
* execution. Intermediate operations * execution. Intermediate operations return streams that are also
* return streams that are also synchronized on the same object. The created * synchronized on the same object. The created stream will behave
* stream will behave identically * identically to the provided stream in all other aspects. Use this to
* to the provided stream in all other aspects. Use this to synchronize * synchronize access to stream's source.
* access to stream's source.
* <p> * <p>
* <i>The returned {@code Stream}'s {@link Stream#iterator() iterator()} and * <i>The returned {@code Stream}'s {@link Stream#iterator() iterator()} and
* {@link Stream#spliterator() * {@link Stream#spliterator() spliterator()} methods return regular
* spliterator()} methods return regular non-synchronized iterators and * non-synchronized iterators and spliterators respectively</i>. It is the
* spliterators respectively</i>. It * user's responsibility to avoid concurrency issues:
* is the user's responsibility to avoid concurrency issues:
* *
* <pre> * <pre>
* synchronized (stream.getMonitor()) { * synchronized (stream.getMonitor()) {
@ -1103,14 +1099,17 @@ public class SyncStreams {
* stream.forEach(System.out::println); // Should never throw a ConcurrentModificationException * stream.forEach(System.out::println); // Should never throw a ConcurrentModificationException
* </pre> * </pre>
* *
* @param <T> the class of objects in the Stream * @param <T>
* @param stream the stream to wrap. * the class of objects in the Stream
* @param monitor the object that the stream will use for synchronization. * @param stream
* When {@code null}, the stream * the stream to wrap.
* will synchronize on itself. * @param monitor
* the object that the stream will use for synchronization. When
* {@code null}, the stream will synchronize on itself.
* @return a {@link SyncStream SyncStream&lt;T&gt;} synchronized on * @return a {@link SyncStream SyncStream&lt;T&gt;} synchronized on
* {@code monitor} and backed by {@code stream}. * {@code monitor} and backed by {@code stream}.
* @throws NullPointerException if {@code stream == null}. * @throws NullPointerException
* if {@code stream == null}.
*/ */
public static <T> SyncStream<T> synchronizedStream(Stream<T> stream, Object monitor) { public static <T> SyncStream<T> synchronizedStream(Stream<T> stream, Object monitor) {
Objects.requireNonNull(stream, "stream cannot be null"); Objects.requireNonNull(stream, "stream cannot be null");
@ -1118,22 +1117,19 @@ public class SyncStreams {
} }
/** /**
* Wraps the given {@link IntStream} to make all * Wraps the given {@link IntStream} to make all <a href=
* <a href=
* "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps"> * "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps">
* terminal operations</a> acquire the provided monitor's lock before * terminal operations</a> acquire the provided monitor's lock before
* execution. Intermediate operations * execution. Intermediate operations return streams that are also
* return streams that are also synchronized on the same object. The created * synchronized on the same object. The created stream will behave
* stream will behave identically * identically to the provided stream in all other aspects. Use this to
* to the provided stream in all other aspects. Use this to synchronize * synchronize access to stream's source.
* access to stream's source.
* <p> * <p>
* <i>The returned {@code IntStream}'s {@link IntStream#iterator() * <i>The returned {@code IntStream}'s {@link IntStream#iterator()
* iterator()} and * iterator()} and {@link IntStream#spliterator() spliterator()} methods
* {@link IntStream#spliterator() spliterator()} methods return regular * return regular non-synchronized iterators and spliterators
* non-synchronized iterators and * respectively</i>. It is the user's responsibility to avoid concurrency
* spliterators respectively</i>. It is the user's responsibility to avoid * issues:
* concurrency issues:
* *
* <pre> * <pre>
* synchronized (stream.getMonitor()) { * synchronized (stream.getMonitor()) {
@ -1152,13 +1148,15 @@ public class SyncStreams {
* stream.forEach(System.out::println); // Should never throw a ConcurrentModificationException * stream.forEach(System.out::println); // Should never throw a ConcurrentModificationException
* </pre> * </pre>
* *
* @param stream the stream to wrap. * @param stream
* @param monitor the object that the stream will use for synchronization. * the stream to wrap.
* When {@code null}, the stream * @param monitor
* will synchronize on itself. * the object that the stream will use for synchronization. When
* {@code null}, the stream will synchronize on itself.
* @return a {@link SyncIntStream} synchronized on {@code monitor} and * @return a {@link SyncIntStream} synchronized on {@code monitor} and
* backed by {@code stream}. * backed by {@code stream}.
* @throws NullPointerException if {@code stream == null}. * @throws NullPointerException
* if {@code stream == null}.
*/ */
public static SyncIntStream synchronizedStream(IntStream stream, Object monitor) { public static SyncIntStream synchronizedStream(IntStream stream, Object monitor) {
Objects.requireNonNull(stream, "stream cannot be null"); Objects.requireNonNull(stream, "stream cannot be null");
@ -1166,22 +1164,19 @@ public class SyncStreams {
} }
/** /**
* Wraps the given {@link LongStream} to make all * Wraps the given {@link LongStream} to make all <a href=
* <a href=
* "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps"> * "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps">
* terminal operations</a> acquire the provided monitor's lock before * terminal operations</a> acquire the provided monitor's lock before
* execution. Intermediate operations * execution. Intermediate operations return streams that are also
* return streams that are also synchronized on the same object. The created * synchronized on the same object. The created stream will behave
* stream will behave identically * identically to the provided stream in all other aspects. Use this to
* to the provided stream in all other aspects. Use this to synchronize * synchronize access to stream's source.
* access to stream's source.
* <p> * <p>
* <i>The returned {@code LongStream}'s {@link LongStream#iterator() * <i>The returned {@code LongStream}'s {@link LongStream#iterator()
* iterator()} and * iterator()} and {@link LongStream#spliterator() spliterator()} methods
* {@link LongStream#spliterator() spliterator()} methods return regular * return regular non-synchronized iterators and spliterators
* non-synchronized iterators and * respectively</i>. It is the user's responsibility to avoid concurrency
* spliterators respectively</i>. It is the user's responsibility to avoid * issues:
* concurrency issues:
* *
* <pre> * <pre>
* synchronized (stream.getMonitor()) { * synchronized (stream.getMonitor()) {
@ -1200,13 +1195,15 @@ public class SyncStreams {
* stream.forEach(System.out::println); // Should never throw a ConcurrentModificationException * stream.forEach(System.out::println); // Should never throw a ConcurrentModificationException
* </pre> * </pre>
* *
* @param stream the stream to wrap. * @param stream
* @param monitor the object that the stream will use for synchronization. * the stream to wrap.
* When {@code null}, the stream * @param monitor
* will synchronize on itself. * the object that the stream will use for synchronization. When
* {@code null}, the stream will synchronize on itself.
* @return a {@link SyncLongStream} synchronized on {@code monitor} and * @return a {@link SyncLongStream} synchronized on {@code monitor} and
* backed by {@code stream}. * backed by {@code stream}.
* @throws NullPointerException if {@code stream == null}. * @throws NullPointerException
* if {@code stream == null}.
*/ */
public static SyncLongStream synchronizedStream(LongStream stream, Object monitor) { public static SyncLongStream synchronizedStream(LongStream stream, Object monitor) {
Objects.requireNonNull(stream, "stream cannot be null"); Objects.requireNonNull(stream, "stream cannot be null");
@ -1214,22 +1211,19 @@ public class SyncStreams {
} }
/** /**
* Wraps the given {@link DoubleStream} to make all * Wraps the given {@link DoubleStream} to make all <a href=
* <a href=
* "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps"> * "https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps">
* terminal operations</a> acquire the provided monitor's lock before * terminal operations</a> acquire the provided monitor's lock before
* execution. Intermediate operations * execution. Intermediate operations return streams that are also
* return streams that are also synchronized on the same object. The created * synchronized on the same object. The created stream will behave
* stream will behave identically * identically to the provided stream in all other aspects. Use this to
* to the provided stream in all other aspects. Use this to synchronize * synchronize access to stream's source.
* access to stream's source.
* <p> * <p>
* <i>The returned {@code DoubleStream}'s {@link DoubleStream#iterator() * <i>The returned {@code DoubleStream}'s {@link DoubleStream#iterator()
* iterator()} and * iterator()} and {@link DoubleStream#spliterator() spliterator()} methods
* {@link DoubleStream#spliterator() spliterator()} methods return regular * return regular non-synchronized iterators and spliterators
* non-synchronized iterators and * respectively</i>. It is the user's responsibility to avoid concurrency
* spliterators respectively</i>. It is the user's responsibility to avoid * issues:
* concurrency issues:
* *
* <pre> * <pre>
* synchronized (stream.getMonitor()) { * synchronized (stream.getMonitor()) {
@ -1248,13 +1242,15 @@ public class SyncStreams {
* stream.forEach(System.out::println); // Should never throw a ConcurrentModificationException * stream.forEach(System.out::println); // Should never throw a ConcurrentModificationException
* </pre> * </pre>
* *
* @param stream the stream to wrap. * @param stream
* @param monitor the object that the stream will use for synchronization. * the stream to wrap.
* When {@code null}, the stream * @param monitor
* will synchronize on itself. * the object that the stream will use for synchronization. When
* {@code null}, the stream will synchronize on itself.
* @return a {@link SyncDoubleStream} synchronized on {@code monitor} and * @return a {@link SyncDoubleStream} synchronized on {@code monitor} and
* backed by {@code stream}. * backed by {@code stream}.
* @throws NullPointerException if {@code stream == null}. * @throws NullPointerException
* if {@code stream == null}.
*/ */
public static SyncDoubleStream synchronizedStream(DoubleStream stream, Object monitor) { public static SyncDoubleStream synchronizedStream(DoubleStream stream, Object monitor) {
Objects.requireNonNull(stream, "stream cannot be null"); Objects.requireNonNull(stream, "stream cannot be null");

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil; package ru.windcorp.jputil;
public class SyntaxException extends Exception { public class SyntaxException extends Exception {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.text.CharacterIterator; import java.text.CharacterIterator;
@ -108,7 +108,7 @@ public class CharArrayIterator implements CharacterIterator {
return pos; return pos;
} }
// @SuppressWarnings("all") Just STFU, this _is_ terrific // @SuppressWarnings("all") Just STFU, this _is_ terrific
// SonarLint: "clone" should not be overridden (java:S2975) // SonarLint: "clone" should not be overridden (java:S2975)
// And I wouldn't have done that if only CharacterIterator had not required // And I wouldn't have done that if only CharacterIterator had not required

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.util.function.IntConsumer; import java.util.function.IntConsumer;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.util.Objects; import java.util.Objects;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.util.Arrays; import java.util.Arrays;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.util.function.IntSupplier; import java.util.function.IntSupplier;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
public class EscapeException extends Exception { public class EscapeException extends Exception {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.text.CharacterIterator; import java.text.CharacterIterator;
@ -103,14 +103,8 @@ public class Escaper {
} }
public static final Escaper JAVA = new Escaper( public static final Escaper JAVA = new Escaper('\\', 'u', "tbnrf'\"".toCharArray(), "\t\b\n\r\f\'\"".toCharArray(),
'\\', true, true);
'u',
"tbnrf'\"".toCharArray(),
"\t\b\n\r\f\'\"".toCharArray(),
true,
true
);
private final char escapeChar; private final char escapeChar;
private final char unicodeEscapeChar; private final char unicodeEscapeChar;
@ -120,14 +114,8 @@ public class Escaper {
private final boolean preferUnicode; private final boolean preferUnicode;
private final boolean strict; private final boolean strict;
protected Escaper( protected Escaper(char escapeChar, char unicodeEscapeChar, char[] safes, char[] unsafes, boolean preferUnicode,
char escapeChar, boolean strict) {
char unicodeEscapeChar,
char[] safes,
char[] unsafes,
boolean preferUnicode,
boolean strict
) {
this.escapeChar = escapeChar; this.escapeChar = escapeChar;
this.unicodeEscapeChar = unicodeEscapeChar; this.unicodeEscapeChar = unicodeEscapeChar;
this.safes = safes; this.safes = safes;
@ -152,8 +140,7 @@ public class Escaper {
for (char c : unsafes) { for (char c : unsafes) {
if (c == escapeChar) if (c == escapeChar)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Unsafe characters contain escape chatacter (escape character is escaped automatically)" "Unsafe characters contain escape chatacter (escape character is escaped automatically)");
);
if (c == unicodeEscapeChar) if (c == unicodeEscapeChar)
throw new IllegalArgumentException("Unsafe characters contain Unicode escape chatacter"); throw new IllegalArgumentException("Unsafe characters contain Unicode escape chatacter");
} }
@ -173,11 +160,7 @@ public class Escaper {
end = Integer.MAX_VALUE; end = Integer.MAX_VALUE;
else else
end = src.getPosition() + length; end = src.getPosition() + length;
while ( while (src.has() && src.getPosition() < end && (until == null || !until.test(src.current())))
src.has() &&
src.getPosition() < end &&
(until == null || !until.test(src.current()))
)
escape(src.consume(), output); escape(src.consume(), output);
} }
@ -225,11 +208,7 @@ public class Escaper {
int result = 0; int result = 0;
while ( while (src.has() && src.getPosition() < end && (until == null || !until.test(src.current()))) {
src.has() &&
src.getPosition() < end &&
(until == null || !until.test(src.current()))
) {
result += getEscapedLength(src.consume()); result += getEscapedLength(src.consume());
} }
@ -257,11 +236,7 @@ public class Escaper {
end = Integer.MAX_VALUE; end = Integer.MAX_VALUE;
else else
end = src.getPosition() + length; end = src.getPosition() + length;
while ( while (src.has() && src.getPosition() < end && (until == null || !until.test(src.current()))) {
src.has() &&
src.getPosition() < end &&
(until == null || !until.test(src.current()))
) {
output.accept(unescapeOneSequence(src)); output.accept(unescapeOneSequence(src));
} }
} }
@ -282,10 +257,8 @@ public class Escaper {
if (src.current() == unicodeEscapeChar) { if (src.current() == unicodeEscapeChar) {
src.next(); src.next();
return (char) (hexValue(src.consume()) << (4 * 3) | return (char) (hexValue(src.consume()) << (4 * 3) | hexValue(src.consume()) << (4 * 2)
hexValue(src.consume()) << (4 * 2) | | hexValue(src.consume()) << (4 * 1) | hexValue(src.consume()) << (4 * 0));
hexValue(src.consume()) << (4 * 1) |
hexValue(src.consume()) << (4 * 0));
} }
int index = ArrayUtil.firstIndexOf(safes, src.current()); int index = ArrayUtil.firstIndexOf(safes, src.current());
@ -315,11 +288,7 @@ public class Escaper {
int result = 0; int result = 0;
while ( while (src.has() && src.getPosition() < end && (until == null || !until.test(src.current()))) {
src.has() &&
src.getPosition() < end &&
(until == null || !until.test(src.current()))
) {
skipOneSequence(src); skipOneSequence(src);
result++; result++;
} }
@ -328,11 +297,7 @@ public class Escaper {
} }
public void skipOneSequence(CharReader src) { public void skipOneSequence(CharReader src) {
if ( if (src.current() == escapeChar && src.next() == unicodeEscapeChar) {
src.current() == escapeChar
&&
src.next() == unicodeEscapeChar
) {
src.advance(4); src.advance(4);
} }
src.next(); src.next();

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.text.CharacterIterator; import java.text.CharacterIterator;
@ -86,7 +86,7 @@ public class FancyCharacterIterator implements CharacterIterator {
return sb.toString(); return sb.toString();
} }
// @SuppressWarnings("all") Just STFU, this _is_ terrific // @SuppressWarnings("all") Just STFU, this _is_ terrific
// SonarLint: "clone" should not be overridden (java:S2975) // SonarLint: "clone" should not be overridden (java:S2975)
// And I wouldn't have done that if only CharacterIterator had not required // And I wouldn't have done that if only CharacterIterator had not required

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
public class IndentedStringBuilder { public class IndentedStringBuilder {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.io.IOException; import java.io.IOException;
@ -41,13 +41,8 @@ public class StringUtil {
private static final String EMPTY_PLACEHOLDER = "[empty]"; private static final String EMPTY_PLACEHOLDER = "[empty]";
private static final String DEFAULT_SEPARATOR = "; "; private static final String DEFAULT_SEPARATOR = "; ";
public static <T> String arrayToString( public static <T> String arrayToString(T[] array, String separator, String empty, String nullPlaceholder,
T[] array, String nullArray) {
String separator,
String empty,
String nullPlaceholder,
String nullArray
) {
if (separator == null) { if (separator == null) {
throw new IllegalArgumentException(new NullPointerException()); throw new IllegalArgumentException(new NullPointerException());
@ -79,13 +74,8 @@ public class StringUtil {
return arrayToString(array, DEFAULT_SEPARATOR); return arrayToString(array, DEFAULT_SEPARATOR);
} }
public static String iteratorToString( public static String iteratorToString(Iterator<?> iterator, String separator, String empty, String nullPlaceholder,
Iterator<?> iterator, String nullIterator) {
String separator,
String empty,
String nullPlaceholder,
String nullIterator
) {
if (separator == null) { if (separator == null) {
throw new IllegalArgumentException(new NullPointerException()); throw new IllegalArgumentException(new NullPointerException());
@ -119,13 +109,8 @@ public class StringUtil {
return iteratorToString(iterator, DEFAULT_SEPARATOR); return iteratorToString(iterator, DEFAULT_SEPARATOR);
} }
public static String iterableToString( public static String iterableToString(Iterable<?> iterable, String separator, String empty, String nullPlaceholder,
Iterable<?> iterable, String nullIterable) {
String separator,
String empty,
String nullPlaceholder,
String nullIterable
) {
if (separator == null) { if (separator == null) {
throw new IllegalArgumentException(new NullPointerException()); throw new IllegalArgumentException(new NullPointerException());
@ -146,14 +131,8 @@ public class StringUtil {
return iterableToString(iterable, DEFAULT_SEPARATOR); return iterableToString(iterable, DEFAULT_SEPARATOR);
} }
public static <T> String supplierToString( public static <T> String supplierToString(IntFunction<T> supplier, int length, String separator, String empty,
IntFunction<T> supplier, String nullPlaceholder, String nullSupplier) {
int length,
String separator,
String empty,
String nullPlaceholder,
String nullSupplier
) {
if (separator == null) if (separator == null)
throw new IllegalArgumentException(new NullPointerException()); throw new IllegalArgumentException(new NullPointerException());
@ -163,28 +142,15 @@ public class StringUtil {
return empty; return empty;
if (length > 0) { if (length > 0) {
return supplierToStringExactly( return supplierToStringExactly(supplier, length, separator, nullPlaceholder);
supplier,
length,
separator,
nullPlaceholder
);
} else { } else {
return supplierToStringUntilNull( return supplierToStringUntilNull(supplier, separator, empty);
supplier,
separator,
empty
);
} }
} }
private static <T> String supplierToStringExactly( private static <T> String supplierToStringExactly(IntFunction<T> supplier, int length, String separator,
IntFunction<T> supplier, String nullPlaceholder) {
int length,
String separator,
String nullPlaceholder
) {
T element = supplier.apply(0); T element = supplier.apply(0);
StringBuilder sb = new StringBuilder(element == null ? nullPlaceholder : element.toString()); StringBuilder sb = new StringBuilder(element == null ? nullPlaceholder : element.toString());
@ -198,11 +164,7 @@ public class StringUtil {
return sb.toString(); return sb.toString();
} }
private static <T> String supplierToStringUntilNull( private static <T> String supplierToStringUntilNull(IntFunction<T> supplier, String separator, String empty) {
IntFunction<T> supplier,
String separator,
String empty
) {
T element = supplier.apply(0); T element = supplier.apply(0);
if (element == null) { if (element == null) {
@ -366,11 +328,7 @@ public class StringUtil {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
charLoop: for (char c : src.toCharArray()) { charLoop: for (char c : src.toCharArray()) {
if ( if ((resultIndex + 1) < arrayLength && test.test(c)) {
(resultIndex + 1) < arrayLength
&&
test.test(c)
) {
result[resultIndex] = resetStringBuilder(sb); result[resultIndex] = resetStringBuilder(sb);
++resultIndex; ++resultIndex;
continue charLoop; continue charLoop;
@ -389,17 +347,17 @@ public class StringUtil {
* index. * index.
* <p> * <p>
* Indices {@code 0} and {@code src.length() - 1} produce {@code str} * Indices {@code 0} and {@code src.length() - 1} produce {@code str}
* excluding * excluding the specified character and {@code ""}.
* the specified character and {@code ""}.
* <p> * <p>
* *
* @param src the String to split * @param src
* @param at index to split at * the String to split
* @throws IllegalArgumentException if the index is out of bounds for * @param at
* {@code src} * index to split at
* @throws IllegalArgumentException
* if the index is out of bounds for {@code src}
* @return an array containing the substrings, in order of encounter in * @return an array containing the substrings, in order of encounter in
* {@code src}. * {@code src}. Its length is always 2.
* Its length is always 2.
*/ */
public static String[] splitAt(String src, int at) { public static String[] splitAt(String src, int at) {
Objects.requireNonNull(src, "src"); Objects.requireNonNull(src, "src");
@ -416,10 +374,7 @@ public class StringUtil {
return new String[] { src.substring(0, src.length() - 1), "" }; return new String[] { src.substring(0, src.length() - 1), "" };
} }
return new String[] { return new String[] { src.substring(0, at), src.substring(at + 1) };
src.substring(0, at),
src.substring(at + 1)
};
} }
/** /**
@ -427,8 +382,7 @@ public class StringUtil {
* indices. * indices.
* <p> * <p>
* Indices {@code 0} and {@code src.length() - 1} produce extra zero-length * Indices {@code 0} and {@code src.length() - 1} produce extra zero-length
* outputs. * outputs. Duplicate indices produce extra zero-length outputs.
* Duplicate indices produce extra zero-length outputs.
* <p> * <p>
* Examples: * Examples:
* *
@ -439,13 +393,14 @@ public class StringUtil {
* splitAt("a.b", 1, 1, 1) -> {"a", "", "", "b"} * splitAt("a.b", 1, 1, 1) -> {"a", "", "", "b"}
* </pre> * </pre>
* *
* @param src the String to split * @param src
* @param at indices to split at, in any order * the String to split
* @throws IllegalArgumentException if some index is out of bounds for * @param at
* {@code src} * indices to split at, in any order
* @throws IllegalArgumentException
* if some index is out of bounds for {@code src}
* @return an array containing the substrings, in order of encounter in * @return an array containing the substrings, in order of encounter in
* {@code src}. * {@code src}. Its length is always {@code at.length + 1}.
* Its length is always {@code at.length + 1}.
*/ */
public static String[] splitAt(String src, int... at) { public static String[] splitAt(String src, int... at) {
Objects.requireNonNull(src, "src"); Objects.requireNonNull(src, "src");
@ -553,10 +508,8 @@ public class StringUtil {
} }
if (endPos < beginPos) { if (endPos < beginPos) {
throw new IllegalArgumentException( throw new IllegalArgumentException("endPos must be greater than or equal to beginPos (endPos=" + endPos
"endPos must be greater than or equal to beginPos (endPos=" + ", beginPos=" + beginPos + ")");
+ endPos + ", beginPos=" + beginPos + ")"
);
} }
if (endPos >= Math.min(a.length, b.length)) { if (endPos >= Math.min(a.length, b.length)) {
@ -592,8 +545,7 @@ public class StringUtil {
/** /**
* Finds and returns the index of the specified appearance of the specified * Finds and returns the index of the specified appearance of the specified
* character * character in the given array. The search starts at index 0.
* in the given array. The search starts at index 0.
* <p> * <p>
* Examples: * Examples:
* <p> * <p>
@ -630,10 +582,12 @@ public class StringUtil {
* </tr> * </tr>
* </table> * </table>
* *
* @param src - the array to search in. * @param src
* @param target - the character to search for. * - the array to search in.
* @param skip - the amount of <code>target</code> characters to be * @param target
* skipped. * - the character to search for.
* @param skip
* - the amount of <code>target</code> characters to be skipped.
* @return The index of the <code>skip+1</code>th <code>target</code> * @return The index of the <code>skip+1</code>th <code>target</code>
* character or -1, if none found. * character or -1, if none found.
* @see StringUtil#indexFromEnd(char[], char, int) * @see StringUtil#indexFromEnd(char[], char, int)
@ -653,8 +607,7 @@ public class StringUtil {
/** /**
* Finds and returns the index of the specified appearance of the specified * Finds and returns the index of the specified appearance of the specified
* character * character in the given array. The search starts at index
* in the given array. The search starts at index
* <code>src.length - 1</code>. * <code>src.length - 1</code>.
* <p> * <p>
* Examples: * Examples:
@ -692,13 +645,15 @@ public class StringUtil {
* </tr> * </tr>
* </table> * </table>
* *
* @param src - the array to search in. * @param src
* @param target - the character to search for. * - the array to search in.
* @param skip - the amount of <code>target</code> characters to be * @param target
* skipped. * - the character to search for.
* @param skip
* - the amount of <code>target</code> characters to be skipped.
* @return The index of the <code>skip+1</code>th * @return The index of the <code>skip+1</code>th
* <code>target</code>character * <code>target</code>character from the end of the array or -1, if
* from the end of the array or -1, if none found. * none found.
* @see StringUtil#indexFromBeginning(char[], char, int) * @see StringUtil#indexFromBeginning(char[], char, int)
*/ */
public static int indexFromEnd(char[] src, char target, int skip) { public static int indexFromEnd(char[] src, char target, int skip) {
@ -873,12 +828,8 @@ public class StringUtil {
return result; return result;
} }
private static void buildCombinations( private static void buildCombinations(StringBuilder sb, Collection<String> result, Iterable<String>[] parts,
StringBuilder sb, int index) {
Collection<String> result,
Iterable<String>[] parts,
int index
) {
if (index >= parts.length) { if (index >= parts.length) {
result.add(sb.toString()); result.add(sb.toString());
} else { } else {
@ -904,13 +855,8 @@ public class StringUtil {
return result; return result;
} }
private static void buildCombinations( private static void buildCombinations(StringBuilder sb, String[] result, int[] resultIndex, String[][] parts,
StringBuilder sb, int index) {
String[] result,
int[] resultIndex,
String[][] parts,
int index
) {
if (index >= parts.length) { if (index >= parts.length) {
result[resultIndex[0]++] = sb.toString(); result[resultIndex[0]++] = sb.toString();
} else { } else {
@ -985,10 +931,7 @@ public class StringUtil {
} }
private static char hexDigit(long value, int digit) { private static char hexDigit(long value, int digit) {
return hexDigit( return hexDigit((int) (value >>> (4 * digit)) & 0xF);
(int) (value >>> (4 * digit))
& 0xF
);
} }
public static char hexDigit(int value) { public static char hexDigit(int value) {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
public class UncheckedEscapeException extends RuntimeException { public class UncheckedEscapeException extends RuntimeException {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars; package ru.windcorp.jputil.chars;
import java.io.IOException; import java.io.IOException;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars.reader; package ru.windcorp.jputil.chars.reader;
/** /**
@ -27,10 +27,9 @@ public abstract class AbstractCharReader implements CharReader {
/** /**
* Current position of this CharReader. The reader maps its input to * Current position of this CharReader. The reader maps its input to
* positions starting from 0. * positions starting from 0. Positions that are negative or lower than 0
* Positions that are negative or lower than 0 are invalid. * are invalid. {@link #current()} will throw an exception if position is
* {@link #current()} * invalid.
* will throw an exception if position is invalid.
*/ */
protected int position = 0; protected int position = 0;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars.reader; package ru.windcorp.jputil.chars.reader;
import java.util.Objects; import java.util.Objects;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars.reader; package ru.windcorp.jputil.chars.reader;
/** /**
@ -51,9 +51,12 @@ public abstract class BufferedCharReader extends AbstractCharReader {
/** /**
* Acquires next characters and stores them in the array. * Acquires next characters and stores them in the array.
* *
* @param buffer the output array * @param buffer
* @param offset index of the first character * the output array
* @param length maximum amount of characters to be pulled * @param offset
* index of the first character
* @param length
* maximum amount of characters to be pulled
* @return the amount of characters actually pulled * @return the amount of characters actually pulled
*/ */
protected int pullChars(char[] buffer, int offset, int length) { protected int pullChars(char[] buffer, int offset, int length) {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars.reader; package ru.windcorp.jputil.chars.reader;
import java.io.IOException; import java.io.IOException;
@ -30,7 +30,7 @@ import ru.windcorp.jputil.chars.Escaper;
*/ */
// SonarLint: Constants should not be defined in interfaces (java:S1214) // SonarLint: Constants should not be defined in interfaces (java:S1214)
// DONE is an essential part of the interface // DONE is an essential part of the interface
@SuppressWarnings("squid:S1214") @SuppressWarnings("squid:S1214")
public interface CharReader { public interface CharReader {
@ -179,8 +179,7 @@ public interface CharReader {
/** /**
* Skips to the end of the current line. Both <code>"\n"</code>, * Skips to the end of the current line. Both <code>"\n"</code>,
* <code>"\r"</code> * <code>"\r"</code> and <code>"\r\n"</code> are considered line separators.
* and <code>"\r\n"</code> are considered line separators.
* *
* @return the amount of characters in the skipped line * @return the amount of characters in the skipped line
*/ */

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars.reader; package ru.windcorp.jputil.chars.reader;
import java.io.InputStream; import java.io.InputStream;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars.reader; package ru.windcorp.jputil.chars.reader;
import java.io.IOException; import java.io.IOException;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.chars.reader; package ru.windcorp.jputil.chars.reader;
import java.util.Objects; import java.util.Objects;
@ -38,8 +38,7 @@ public class StringCharReader extends AbstractCharReader {
int end = offset + length; int end = offset + length;
if (end > str.length() || offset < 0) if (end > str.length() || offset < 0)
throw new IllegalArgumentException( throw new IllegalArgumentException(
"String contains [0; " + str.length() + "), requested [" + offset + "; " + end + ")" "String contains [0; " + str.length() + "), requested [" + offset + "; " + end + ")");
);
this.offset = offset; this.offset = offset;
this.length = length; this.length = length;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.functions; package ru.windcorp.jputil.functions;
@FunctionalInterface @FunctionalInterface

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.functions; package ru.windcorp.jputil.functions;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@ -44,9 +44,16 @@ public interface ThrowingBiConsumer<T, U, E extends Exception> {
} }
public static <T, U, E extends Exception> ThrowingBiConsumer<T, U, E> concat( public static <T, U, E extends Exception> ThrowingBiConsumer<T, U, E> concat(
ThrowingBiConsumer<? super T, ? super U, ? extends E> first, ThrowingBiConsumer<? super T, ? super U, ? extends E> first,
ThrowingBiConsumer<? super T, ? super U, ? extends E> second ThrowingBiConsumer<? super T, ? super U, ? extends E> second) {
) { return (t, u) -> {
first.accept(t, u);
second.accept(t, u);
};
}
public static <T, U, E extends Exception> ThrowingBiConsumer<T, U, E> concat(BiConsumer<? super T, ? super U> first,
ThrowingBiConsumer<? super T, ? super U, E> second) {
return (t, u) -> { return (t, u) -> {
first.accept(t, u); first.accept(t, u);
second.accept(t, u); second.accept(t, u);
@ -54,19 +61,7 @@ public interface ThrowingBiConsumer<T, U, E extends Exception> {
} }
public static <T, U, E extends Exception> ThrowingBiConsumer<T, U, E> concat( public static <T, U, E extends Exception> ThrowingBiConsumer<T, U, E> concat(
BiConsumer<? super T, ? super U> first, ThrowingBiConsumer<? super T, ? super U, E> first, BiConsumer<? super T, ? super U> second) {
ThrowingBiConsumer<? super T, ? super U, E> second
) {
return (t, u) -> {
first.accept(t, u);
second.accept(t, u);
};
}
public static <T, U, E extends Exception> ThrowingBiConsumer<T, U, E> concat(
ThrowingBiConsumer<? super T, ? super U, E> first,
BiConsumer<? super T, ? super U> second
) {
return (t, u) -> { return (t, u) -> {
first.accept(t, u); first.accept(t, u);
second.accept(t, u); second.accept(t, u);

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.functions; package ru.windcorp.jputil.functions;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@ -39,30 +39,24 @@ public interface ThrowingConsumer<T, E extends Exception> {
}; };
} }
public static <T, E extends Exception> ThrowingConsumer<T, E> concat( public static <T, E extends Exception> ThrowingConsumer<T, E> concat(ThrowingConsumer<? super T, ? extends E> first,
ThrowingConsumer<? super T, ? extends E> first, ThrowingConsumer<? super T, ? extends E> second) {
ThrowingConsumer<? super T, ? extends E> second
) {
return t -> { return t -> {
first.accept(t); first.accept(t);
second.accept(t); second.accept(t);
}; };
} }
public static <T, E extends Exception> ThrowingConsumer<T, E> concat( public static <T, E extends Exception> ThrowingConsumer<T, E> concat(Consumer<? super T> first,
Consumer<? super T> first, ThrowingConsumer<? super T, ? extends E> second) {
ThrowingConsumer<? super T, ? extends E> second
) {
return t -> { return t -> {
first.accept(t); first.accept(t);
second.accept(t); second.accept(t);
}; };
} }
public static <T, E extends Exception> ThrowingConsumer<T, E> concat( public static <T, E extends Exception> ThrowingConsumer<T, E> concat(ThrowingConsumer<? super T, ? extends E> first,
ThrowingConsumer<? super T, ? extends E> first, Consumer<? super T> second) {
Consumer<? super T> second
) {
return t -> { return t -> {
first.accept(t); first.accept(t);
second.accept(t); second.accept(t);

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.functions; package ru.windcorp.jputil.functions;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@ -28,10 +28,8 @@ public interface ThrowingFunction<T, R, E extends Exception> {
R apply(T t) throws E; R apply(T t) throws E;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
default Function<T, R> withHandler( default Function<T, R> withHandler(BiConsumer<? super T, ? super E> handler,
BiConsumer<? super T, ? super E> handler, Function<? super T, ? extends R> value) {
Function<? super T, ? extends R> value
) {
return t -> { return t -> {
try { try {
return apply(t); return apply(t);
@ -58,23 +56,18 @@ public interface ThrowingFunction<T, R, E extends Exception> {
} }
public static <T, R, I, E extends Exception> ThrowingFunction<T, R, E> compose( public static <T, R, I, E extends Exception> ThrowingFunction<T, R, E> compose(
ThrowingFunction<? super T, I, ? extends E> first, ThrowingFunction<? super T, I, ? extends E> first,
ThrowingFunction<? super I, ? extends R, ? extends E> second ThrowingFunction<? super I, ? extends R, ? extends E> second) {
) { return t -> second.apply(first.apply(t));
}
public static <T, R, I, E extends Exception> ThrowingFunction<T, R, E> compose(Function<? super T, I> first,
ThrowingFunction<? super I, ? extends R, E> second) {
return t -> second.apply(first.apply(t)); return t -> second.apply(first.apply(t));
} }
public static <T, R, I, E extends Exception> ThrowingFunction<T, R, E> compose( public static <T, R, I, E extends Exception> ThrowingFunction<T, R, E> compose(
Function<? super T, I> first, ThrowingFunction<? super T, I, E> first, Function<? super I, ? extends R> second) {
ThrowingFunction<? super I, ? extends R, E> second
) {
return t -> second.apply(first.apply(t));
}
public static <T, R, I, E extends Exception> ThrowingFunction<T, R, E> compose(
ThrowingFunction<? super T, I, E> first,
Function<? super I, ? extends R> second
) {
return t -> second.apply(first.apply(t)); return t -> second.apply(first.apply(t));
} }

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.functions; package ru.windcorp.jputil.functions;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -38,10 +38,8 @@ public interface ThrowingRunnable<E extends Exception> {
}; };
} }
public static <E extends Exception> ThrowingRunnable<E> concat( public static <E extends Exception> ThrowingRunnable<E> concat(ThrowingRunnable<? extends E> first,
ThrowingRunnable<? extends E> first, ThrowingRunnable<? extends E> second) {
ThrowingRunnable<? extends E> second
) {
return () -> { return () -> {
first.run(); first.run();
second.run(); second.run();

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.functions; package ru.windcorp.jputil.functions;
import java.util.function.Consumer; import java.util.function.Consumer;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.iterators; package ru.windcorp.jputil.iterators;
import java.util.Iterator; import java.util.Iterator;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.iterators; package ru.windcorp.jputil.iterators;
import java.util.Iterator; import java.util.Iterator;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.iterators; package ru.windcorp.jputil.iterators;
import java.util.Iterator; import java.util.Iterator;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.iterators; package ru.windcorp.jputil.iterators;
import java.util.Iterator; import java.util.Iterator;
@ -49,10 +49,8 @@ public class RangeIterator<E> implements Iterator<E> {
public E next() { public E next() {
update(); update();
if (nextIndex >= from + amount) { if (nextIndex >= from + amount) {
throw new NoSuchElementException( throw new NoSuchElementException("RangeIterator about to retrieve element " + nextIndex
"RangeIterator about to retrieve element " + nextIndex + " which exceeds upper boundary " + (from + amount));
+ " which exceeds upper boundary " + (from + amount)
);
} }
E result = parent.next(); E result = parent.next();

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.iterators; package ru.windcorp.jputil.iterators;
import java.util.ArrayList; import java.util.ArrayList;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
public abstract class AbstractSelectorOperator implements SelectorOperator { public abstract class AbstractSelectorOperator implements SelectorOperator {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import ru.windcorp.jputil.SyntaxException; import ru.windcorp.jputil.SyntaxException;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import ru.windcorp.jputil.SyntaxException; import ru.windcorp.jputil.SyntaxException;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.Deque; import java.util.Deque;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.Deque; import java.util.Deque;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.Deque; import java.util.Deque;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.Deque; import java.util.Deque;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.Deque; import java.util.Deque;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.function.Predicate; import java.util.function.Predicate;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.function.Predicate; import java.util.function.Predicate;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.Deque; import java.util.Deque;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.jputil.selectors; package ru.windcorp.jputil.selectors;
import java.util.ArrayList; import java.util.ArrayList;
@ -37,7 +37,7 @@ public class SelectorSystem<T> {
private final Collection<Selector<T>> selectors = Collections.synchronizedCollection(new ArrayList<Selector<T>>()); private final Collection<Selector<T>> selectors = Collections.synchronizedCollection(new ArrayList<Selector<T>>());
private final Collection<SelectorOperator> operators = Collections private final Collection<SelectorOperator> operators = Collections
.synchronizedCollection(new ArrayList<SelectorOperator>()); .synchronizedCollection(new ArrayList<SelectorOperator>());
private String stackPrefix = null; private String stackPrefix = null;

View File

@ -18,177 +18,6 @@
package ru.windcorp.progressia; package ru.windcorp.progressia;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.apache.logging.log4j.LogManager;
import ru.windcorp.progressia.common.util.crash.CrashReports;
/**
* A class providing access to build metadata.
*/
public class Progressia { public class Progressia {
private static final String NAME = "Progressia";
private static String version;
private static String gitCommit;
private static String gitBranch;
private static String buildId;
static {
try {
Manifest manifest = findManifest();
if (manifest == null) {
setDevelopmentMetadata();
LogManager.getLogger().info(
"Manifest with Specification-Title not found. "
+ "Either you are in a development environment or something has gone horribly wrong with classloaders."
);
} else {
fillMetadata(manifest);
}
} catch (Throwable t) {
CrashReports.crash(t, "Something went wrong while loading metadata");
}
}
private static Manifest findManifest() {
try {
Enumeration<URL> resources = Progressia.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
Collection<IOException> exceptions = new ArrayList<>();
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
try {
Manifest manifest = new Manifest(url.openStream());
Attributes mainAttributes = manifest.getMainAttributes();
if (NAME.equals(mainAttributes.getValue("Specification-Title"))) {
return manifest;
}
} catch (IOException e) {
exceptions.add(e);
}
}
if (exceptions.isEmpty()) {
return null;
}
IOException scapegoat = null;
for (IOException e : exceptions) {
if (scapegoat == null) {
scapegoat = e;
} else {
scapegoat.addSuppressed(e);
}
}
throw CrashReports.report(scapegoat, "Could not read manifest");
} catch (IOException e) {
throw CrashReports.report(e, "Could not read manifest");
}
}
private static void setDevelopmentMetadata() {
version = "dev";
gitCommit = "-";
gitBranch = "-";
buildId = "-";
}
private static void fillMetadata(Manifest manifest) {
version = getAttributeOrCrash(manifest, "Implementation-Version");
gitCommit = getAttributeOrCrash(manifest, "Implementation-Version-Git-Commit");
gitBranch = getAttributeOrCrash(manifest, "Implementation-Version-Git-Branch");
buildId = getAttributeOrCrash(manifest, "Implementation-Version-BuildId");
}
private static String getAttributeOrCrash(Manifest manifest, String key) {
String result = manifest.getMainAttributes().getValue(key);
if (result == null) {
throw CrashReports.report(null, "Manifest exists but attribute " + key + " not found");
}
return result;
}
public static String getName() {
return NAME;
}
/**
* Returns the version of the game as a String. Version data is retrieved
* from a {@code META-INF/MANIFEST.MF} file located in the main JAR. Version
* format depends on way the game was built:
* <ul>
* <li><code>dev</code> if no matching manifest was found, e.g. when launching from an IDE</li>
* <li>The value of <code>Implementation-Version</code> specified in the manifest:
* <ul>
* <li>[Stage-]Major.Minor.Patch, e.g. <code>alpha-0.3.2</code> or <code>1.4.2</code>, for released versions</li>
* <li>BuildId, e.g. <code>WJ7</code>, for snapshots built by automation systems</li>
* <li>YYYY-MM-DD, e.g. <code>2021-12-32</code>, for snapshots built manually</li>
* </ul>
* </li>
* </ul>
*
* @return the version
*/
public static String getVersion() {
return version;
}
public static String getFullerVersion() {
if (isDefaultGitBranch() || "-".equals(gitBranch)) {
return version;
} else {
return String.format("%s/%s", version, gitBranch);
}
}
/**
* @return the buildId or <code>"-"</code>
*/
public static String getBuildId() {
return buildId;
}
/**
* @return the Git commit or <code>"-"</code>
*/
public static String getGitCommit() {
return gitCommit;
}
public static String getGitCommitShort() {
if (gitCommit == null || "-".equals(gitCommit)) {
return gitCommit;
}
return gitCommit.substring(0, Math.min(7, gitCommit.length()));
}
/**
* @return the Git branch or <code>"-"</code>
*/
public static String getGitBranch() {
return gitBranch;
}
public static boolean isDefaultGitBranch() {
return "master".equals(gitBranch) || "main".equals(gitBranch);
}
public static String getFullVersion() {
return String.format("%s/%s/%s/%s", version, gitBranch, getGitCommitShort(), buildId);
}
} }

View File

@ -18,37 +18,22 @@
package ru.windcorp.progressia; package ru.windcorp.progressia;
import org.apache.logging.log4j.LogManager;
import ru.windcorp.progressia.client.graphics.GUI;
import ru.windcorp.progressia.common.util.crash.CrashReports; import ru.windcorp.progressia.common.util.crash.CrashReports;
import ru.windcorp.progressia.common.util.crash.analyzers.OutOfMemoryAnalyzer; import ru.windcorp.progressia.common.util.crash.analyzers.OutOfMemoryAnalyzer;
import ru.windcorp.progressia.common.util.crash.providers.*; import ru.windcorp.progressia.common.util.crash.providers.*;
import ru.windcorp.progressia.test.LayerTitle;
public class ProgressiaLauncher { public class ProgressiaLauncher {
public static String[] arguments; public static String[] arguments;
private static Proxy proxy;
public static void launch(String[] args, Proxy proxy) { public static void launch(String[] args, Proxy proxy) {
arguments = args.clone(); arguments = args.clone();
setupCrashReports(); setupCrashReports();
LogManager.getRootLogger().info("Launching " + Progressia.getName() + " version " + Progressia.getFullVersion());
proxy.initialize(); proxy.initialize();
ProgressiaLauncher.proxy = proxy;
GUI.addTopLayer(new LayerTitle("Title"));
}
public static Proxy getProxy() {
return proxy;
} }
private static void setupCrashReports() { private static void setupCrashReports() {
// Context providers // Context providers
CrashReports.registerProvider(new VersionProvider());
CrashReports.registerProvider(new OSContextProvider()); CrashReports.registerProvider(new OSContextProvider());
CrashReports.registerProvider(new RAMContextProvider()); CrashReports.registerProvider(new RAMContextProvider());
CrashReports.registerProvider(new JavaVersionContextProvider()); CrashReports.registerProvider(new JavaVersionContextProvider());

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia; package ru.windcorp.progressia;
public interface Proxy { public interface Proxy {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client; package ru.windcorp.progressia.client;
import ru.windcorp.progressia.client.comms.DefaultClientCommsListener; import ru.windcorp.progressia.client.comms.DefaultClientCommsListener;
@ -69,11 +69,7 @@ public class Client {
return; return;
} }
getCamera().setAnchor( getCamera().setAnchor(new EntityAnchor(getWorld().getEntityRenderable(entity)));
new EntityAnchor(
getWorld().getEntityRenderable(entity)
)
);
} }
} }

View File

@ -25,12 +25,12 @@ import ru.windcorp.progressia.client.graphics.backend.RenderTaskQueue;
import ru.windcorp.progressia.client.graphics.flat.FlatRenderProgram; import ru.windcorp.progressia.client.graphics.flat.FlatRenderProgram;
import ru.windcorp.progressia.client.graphics.font.GNUUnifontLoader; import ru.windcorp.progressia.client.graphics.font.GNUUnifontLoader;
import ru.windcorp.progressia.client.graphics.font.Typefaces; import ru.windcorp.progressia.client.graphics.font.Typefaces;
import ru.windcorp.progressia.client.graphics.gui.ColorScheme;
import ru.windcorp.progressia.client.graphics.texture.Atlases; import ru.windcorp.progressia.client.graphics.texture.Atlases;
import ru.windcorp.progressia.client.graphics.world.WorldRenderProgram; import ru.windcorp.progressia.client.graphics.world.WorldRenderProgram;
import ru.windcorp.progressia.client.localization.Localizer; import ru.windcorp.progressia.client.localization.Localizer;
import ru.windcorp.progressia.common.resource.ResourceManager; import ru.windcorp.progressia.common.resource.ResourceManager;
import ru.windcorp.progressia.common.util.crash.CrashReports; import ru.windcorp.progressia.common.util.crash.CrashReports;
import ru.windcorp.progressia.server.ServerState;
import ru.windcorp.progressia.test.TestContent; import ru.windcorp.progressia.test.TestContent;
import ru.windcorp.progressia.test.TestMusicPlayer; import ru.windcorp.progressia.test.TestMusicPlayer;
@ -38,21 +38,16 @@ public class ClientProxy implements Proxy {
@Override @Override
public void initialize() { public void initialize() {
GraphicsBackend.initialize(); GraphicsBackend.initialize();
try { try {
RenderTaskQueue.waitAndInvoke(FlatRenderProgram::init); RenderTaskQueue.waitAndInvoke(FlatRenderProgram::init);
RenderTaskQueue.waitAndInvoke(WorldRenderProgram::init); RenderTaskQueue.waitAndInvoke(WorldRenderProgram::init);
RenderTaskQueue.waitAndInvoke( RenderTaskQueue.waitAndInvoke(() -> Typefaces
() -> Typefaces .setDefault(GNUUnifontLoader.load(ResourceManager.getResource("assets/unifont-13.0.03.hex.gz"))));
.setDefault(GNUUnifontLoader.load(ResourceManager.getResource("assets/unifont-13.0.03.hex.gz")))
);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw CrashReports.report(e, "ClientProxy failed"); throw CrashReports.report(e, "ClientProxy failed");
} }
ColorScheme.load(ResourceManager.getResource("assets/default.colorScheme"));
Localizer.getInstance().setLanguage("en-US"); Localizer.getInstance().setLanguage("en-US");
TestContent.registerContent(); TestContent.registerContent();
@ -61,6 +56,10 @@ public class ClientProxy implements Proxy {
AudioSystem.initialize(); AudioSystem.initialize();
ServerState.startServer();
ClientState.connectToLocalServer();
TestMusicPlayer.start(); TestMusicPlayer.start();
} }
} }

View File

@ -20,13 +20,10 @@ package ru.windcorp.progressia.client;
import ru.windcorp.progressia.client.comms.localhost.LocalServerCommsChannel; import ru.windcorp.progressia.client.comms.localhost.LocalServerCommsChannel;
import ru.windcorp.progressia.client.graphics.GUI; import ru.windcorp.progressia.client.graphics.GUI;
import ru.windcorp.progressia.client.graphics.Layer;
import ru.windcorp.progressia.client.graphics.world.LayerWorld; import ru.windcorp.progressia.client.graphics.world.LayerWorld;
import ru.windcorp.progressia.common.world.DefaultWorldData; import ru.windcorp.progressia.common.world.DefaultWorldData;
import ru.windcorp.progressia.client.localization.MutableStringLocalized;
import ru.windcorp.progressia.server.ServerState; import ru.windcorp.progressia.server.ServerState;
import ru.windcorp.progressia.test.LayerAbout; import ru.windcorp.progressia.test.LayerAbout;
import ru.windcorp.progressia.test.LayerTestText;
import ru.windcorp.progressia.test.LayerTestUI; import ru.windcorp.progressia.test.LayerTestUI;
import ru.windcorp.progressia.test.TestContent; import ru.windcorp.progressia.test.TestContent;
@ -46,48 +43,18 @@ public class ClientState {
DefaultWorldData world = new DefaultWorldData(); DefaultWorldData world = new DefaultWorldData();
LocalServerCommsChannel channel = new LocalServerCommsChannel( LocalServerCommsChannel channel = new LocalServerCommsChannel(ServerState.getInstance());
ServerState.getInstance()
);
Client client = new Client(world, channel); Client client = new Client(world, channel);
channel.connect(TestContent.PLAYER_LOGIN); channel.connect(TestContent.PLAYER_LOGIN);
setInstance(client); setInstance(client);
displayLoadingScreen();
} GUI.addBottomLayer(new LayerWorld(client));
GUI.addTopLayer(new LayerTestUI());
GUI.addTopLayer(new LayerAbout());
private static void displayLoadingScreen() {
GUI.addTopLayer(new LayerTestText("Text", new MutableStringLocalized("LayerText.Load"), layer -> {
Client client = ClientState.getInstance();
// TODO refacetor and remove
if (client != null) {
client.getComms().processPackets();
}
if (client != null && client.getLocalPlayer().hasEntity()) {
GUI.removeLayer(layer);
// TODO refactor, this shouldn't be here
LayerWorld layerWorld = new LayerWorld(client);
LayerTestUI layerUI = new LayerTestUI();
LayerAbout layerAbout = new LayerAbout();
GUI.addBottomLayer(layerWorld);
GUI.addTopLayer(layerUI);
GUI.addTopLayer(layerAbout);
}
}));
}
public static void disconnectFromLocalServer() {
getInstance().getComms().disconnect();
for (Layer layer : GUI.getLayers()) {
GUI.removeLayer(layer);
}
} }
private ClientState() { private ClientState() {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client; package ru.windcorp.progressia.client;
import ru.windcorp.progressia.ProgressiaLauncher; import ru.windcorp.progressia.ProgressiaLauncher;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio; package ru.windcorp.progressia.client.audio;
public enum AudioFormat { public enum AudioFormat {

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio; package ru.windcorp.progressia.client.audio;
import org.lwjgl.openal.*; import org.lwjgl.openal.*;
@ -43,10 +43,7 @@ public class AudioManager {
private static Speaker musicSpeaker; private static Speaker musicSpeaker;
public static void initAL() { public static void initAL() {
String defaultDeviceName = alcGetString( String defaultDeviceName = alcGetString(0, ALC_DEFAULT_DEVICE_SPECIFIER);
0,
ALC_DEFAULT_DEVICE_SPECIFIER
);
device = alcOpenDevice(defaultDeviceName); device = alcOpenDevice(defaultDeviceName);
@ -75,10 +72,7 @@ public class AudioManager {
lastSoundIndex = 0; lastSoundIndex = 0;
} }
speaker = soundSpeakers.get(lastSoundIndex); speaker = soundSpeakers.get(lastSoundIndex);
} while ( } while (speaker.getState().equals(Speaker.State.PLAYING_LOOP));
speaker.getState()
.equals(Speaker.State.PLAYING_LOOP)
);
return speaker; return speaker;
} }

View File

@ -21,9 +21,9 @@ import ru.windcorp.progressia.client.audio.backend.SoundType;
import ru.windcorp.progressia.common.util.namespaces.NamespacedInstanceRegistry; import ru.windcorp.progressia.common.util.namespaces.NamespacedInstanceRegistry;
public class AudioRegistry extends NamespacedInstanceRegistry<SoundType> { public class AudioRegistry extends NamespacedInstanceRegistry<SoundType> {
private static final AudioRegistry INSTANCE = new AudioRegistry(); private static final AudioRegistry INSTANCE = new AudioRegistry();
/** /**
* @return the instance * @return the instance
*/ */

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio; package ru.windcorp.progressia.client.audio;
import ru.windcorp.progressia.common.resource.ResourceManager; import ru.windcorp.progressia.common.resource.ResourceManager;
@ -29,10 +29,7 @@ public class AudioSystem {
} }
static void loadAudioData() { static void loadAudioData() {
AudioManager.loadSound( AudioManager.loadSound(ResourceManager.getResource("assets/sounds/block_destroy_clap.ogg"),
ResourceManager.getResource("assets/sounds/block_destroy_clap.ogg"), "Progressia:BlockDestroy", AudioFormat.MONO);
"Progressia:BlockDestroy",
AudioFormat.MONO
);
} }
} }

View File

@ -15,18 +15,15 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio; package ru.windcorp.progressia.client.audio;
import glm.vec._3.Vec3; import glm.vec._3.Vec3;
import ru.windcorp.progressia.client.audio.backend.SoundType; import ru.windcorp.progressia.client.audio.backend.SoundType;
import ru.windcorp.progressia.client.audio.backend.Speaker; import ru.windcorp.progressia.client.audio.backend.Speaker;
public class Music public class Music extends Sound {
extends Sound {
public Music(SoundType soundType, int timeLength, float pitch, float gain) { public Music(SoundType soundType, int timeLength, float pitch, float gain) {
super(soundType, timeLength, new Vec3(), new Vec3(), pitch, gain); super(soundType, timeLength, new Vec3(), new Vec3(), pitch, gain);
} }
@ -47,7 +44,7 @@ public class Music
protected Speaker initSpeaker() { protected Speaker initSpeaker() {
return AudioManager.initMusicSpeaker(soundType); return AudioManager.initMusicSpeaker(soundType);
} }
@Override @Override
public void setPosition(Vec3 position) { public void setPosition(Vec3 position) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio; package ru.windcorp.progressia.client.audio;
import glm.vec._3.Vec3; import glm.vec._3.Vec3;
@ -29,9 +29,9 @@ public class Sound {
protected float pitch = 1.0f; protected float pitch = 1.0f;
protected float gain = 1.0f; protected float gain = 1.0f;
protected int timeLength = 0; protected int timeLength = 0;
protected SoundType soundType; protected SoundType soundType;
public Sound(SoundType soundType) { public Sound(SoundType soundType) {
this.soundType = soundType; this.soundType = soundType;
} }
@ -39,37 +39,23 @@ public class Sound {
public Sound(String id) { public Sound(String id) {
this(AudioRegistry.getInstance().get(id)); this(AudioRegistry.getInstance().get(id));
} }
public Sound( public Sound(String id, int timeLength, Vec3 position, Vec3 velocity, float pitch, float gain) {
String id,
int timeLength,
Vec3 position,
Vec3 velocity,
float pitch,
float gain
) {
this(id); this(id);
this.position = position; this.position = position;
this.velocity = velocity; this.velocity = velocity;
this.pitch = pitch; this.pitch = pitch;
this.gain = gain; this.gain = gain;
} }
public Sound( public Sound(SoundType soundType, int timeLength, Vec3 position, Vec3 velocity, float pitch, float gain) {
SoundType soundType,
int timeLength,
Vec3 position,
Vec3 velocity,
float pitch,
float gain
) {
this(soundType); this(soundType);
this.position = position; this.position = position;
this.velocity = velocity; this.velocity = velocity;
this.pitch = pitch; this.pitch = pitch;
this.gain = gain; this.gain = gain;
} }
protected Speaker initSpeaker() { protected Speaker initSpeaker() {
return AudioManager.initSpeaker(soundType); return AudioManager.initSpeaker(soundType);
} }
@ -119,7 +105,7 @@ public class Sound {
public float getPitch() { public float getPitch() {
return pitch; return pitch;
} }
public double getDuration() { public double getDuration() {
return soundType.getDuration(); return soundType.getDuration();
} }

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio.backend; package ru.windcorp.progressia.client.audio.backend;
import org.lwjgl.BufferUtils; import org.lwjgl.BufferUtils;
@ -39,12 +39,7 @@ public class AudioReader {
ShortBuffer rawAudio = decodeVorbis(resource, channelBuffer, rateBuffer); ShortBuffer rawAudio = decodeVorbis(resource, channelBuffer, rateBuffer);
return new SoundType( return new SoundType(id, rawAudio, format, rateBuffer.get(0));
id,
rawAudio,
format,
rateBuffer.get(0)
);
} }
public static SoundType readAsMono(Resource resource, String id) { public static SoundType readAsMono(Resource resource, String id) {
@ -55,15 +50,7 @@ public class AudioReader {
return readAsSpecified(resource, id, AL_FORMAT_STEREO16); return readAsSpecified(resource, id, AL_FORMAT_STEREO16);
} }
private static ShortBuffer decodeVorbis( private static ShortBuffer decodeVorbis(Resource dataToDecode, IntBuffer channelsBuffer, IntBuffer rateBuffer) {
Resource dataToDecode, return stb_vorbis_decode_memory(dataToDecode.readAsBytes(), channelsBuffer, rateBuffer);
IntBuffer channelsBuffer,
IntBuffer rateBuffer
) {
return stb_vorbis_decode_memory(
dataToDecode.readAsBytes(),
channelsBuffer,
rateBuffer
);
} }
} }

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio.backend; package ru.windcorp.progressia.client.audio.backend;
import glm.vec._3.Vec3; import glm.vec._3.Vec3;
@ -55,9 +55,8 @@ public class Listener {
if (isInWorld) { if (isInWorld) {
if (wasInWorld) { if (wasInWorld) {
velocity.set(camera.getLastAnchorPosition()).sub(position).div( velocity.set(camera.getLastAnchorPosition()).sub(position)
(float) GraphicsInterface.getFrameLength() .div((float) GraphicsInterface.getFrameLength());
);
} else { } else {
// If !wasInWorld, previous position is nonsence. Assume 0. // If !wasInWorld, previous position is nonsence. Assume 0.
velocity.set(0); velocity.set(0);
@ -72,9 +71,9 @@ public class Listener {
} }
/* /*
* Only apply if there is a chance that params changed. * Only apply if there is a chance that params changed. This can only
* This can only happen if we are in world now (isInWorld) or we just * happen if we are in world now (isInWorld) or we just left world
* left world (wasInWorld, then we need to reset). * (wasInWorld, then we need to reset).
*/ */
if (isInWorld || wasInWorld) { if (isInWorld || wasInWorld) {
applyParams(); applyParams();
@ -91,17 +90,7 @@ public class Listener {
private void applyParams() { private void applyParams() {
alListener3f(AL_POSITION, position.x, position.y, position.z); alListener3f(AL_POSITION, position.x, position.y, position.z);
alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z); alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z);
alListenerfv( alListenerfv(AL_ORIENTATION, new float[] { oriAt.x, oriAt.y, oriAt.z, oriUp.x, oriUp.y, oriUp.z });
AL_ORIENTATION,
new float[] {
oriAt.x,
oriAt.y,
oriAt.z,
oriUp.x,
oriUp.y,
oriUp.z
}
);
} }
} }

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio.backend; package ru.windcorp.progressia.client.audio.backend;
import ru.windcorp.progressia.common.util.namespaces.Namespaced; import ru.windcorp.progressia.common.util.namespaces.Namespaced;
@ -34,12 +34,7 @@ public class SoundType extends Namespaced {
private int audioBuffer; private int audioBuffer;
private double duration; private double duration;
public SoundType( public SoundType(String id, ShortBuffer rawAudio, int format, int sampleRate) {
String id,
ShortBuffer rawAudio,
int format,
int sampleRate
) {
super(id); super(id);
this.rawAudio = rawAudio; this.rawAudio = rawAudio;
this.sampleRate = sampleRate; this.sampleRate = sampleRate;
@ -56,7 +51,7 @@ public class SoundType extends Namespaced {
public void initSpeaker(Speaker speaker) { public void initSpeaker(Speaker speaker) {
speaker.setAudioData(audioBuffer); speaker.setAudioData(audioBuffer);
} }
public double getDuration() { public double getDuration() {
return duration; return duration;
} }

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.audio.backend; package ru.windcorp.progressia.client.audio.backend;
import glm.vec._3.Vec3; import glm.vec._3.Vec3;
@ -24,9 +24,7 @@ import static org.lwjgl.openal.AL11.*;
public class Speaker { public class Speaker {
public enum State { public enum State {
NOT_PLAYING, NOT_PLAYING, PLAYING, PLAYING_LOOP
PLAYING,
PLAYING_LOOP
} }
// Buffers // Buffers
@ -49,13 +47,7 @@ public class Speaker {
setAudioData(audioData); setAudioData(audioData);
} }
public Speaker( public Speaker(int audioData, Vec3 position, Vec3 velocity, float pitch, float gain) {
int audioData,
Vec3 position,
Vec3 velocity,
float pitch,
float gain
) {
setAudioData(audioData); setAudioData(audioData);
setPosition(position); setPosition(position);
setVelocity(velocity); setVelocity(velocity);
@ -63,12 +55,7 @@ public class Speaker {
setGain(gain); setGain(gain);
} }
public Speaker( public Speaker(Vec3 position, Vec3 velocity, float pitch, float gain) {
Vec3 position,
Vec3 velocity,
float pitch,
float gain
) {
setPosition(position); setPosition(position);
setVelocity(velocity); setVelocity(velocity);
setPitch(pitch); setPitch(pitch);

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms; package ru.windcorp.progressia.client.comms;
import java.io.IOException; import java.io.IOException;
@ -39,9 +39,7 @@ public class DefaultClientCommsListener implements CommsListener {
@Override @Override
public void onPacketReceived(Packet packet) { public void onPacketReceived(Packet packet) {
if (packet instanceof PacketAffectWorld) { if (packet instanceof PacketAffectWorld) {
((PacketAffectWorld) packet).apply( ((PacketAffectWorld) packet).apply(getClient().getWorld().getData());
getClient().getWorld().getData()
);
} else if (packet instanceof PacketSetLocalPlayer) { } else if (packet instanceof PacketSetLocalPlayer) {
setLocalPlayer((PacketSetLocalPlayer) packet); setLocalPlayer((PacketSetLocalPlayer) packet);
} }

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms; package ru.windcorp.progressia.client.comms;
import ru.windcorp.progressia.common.comms.CommsChannel; import ru.windcorp.progressia.common.comms.CommsChannel;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms.controls; package ru.windcorp.progressia.client.comms.controls;
import ru.windcorp.progressia.common.util.namespaces.Namespaced; import ru.windcorp.progressia.common.util.namespaces.Namespaced;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms.controls; package ru.windcorp.progressia.client.comms.controls;
import ru.windcorp.progressia.client.graphics.input.InputEvent; import ru.windcorp.progressia.client.graphics.input.InputEvent;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms.controls; package ru.windcorp.progressia.client.comms.controls;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@ -33,17 +33,12 @@ public class ControlTriggerLambda extends ControlTriggerInputBased {
private final Predicate<InputEvent> predicate; private final Predicate<InputEvent> predicate;
private final BiConsumer<InputEvent, ControlData> dataWriter; private final BiConsumer<InputEvent, ControlData> dataWriter;
public ControlTriggerLambda( public ControlTriggerLambda(String id, Predicate<InputEvent> predicate,
String id, BiConsumer<InputEvent, ControlData> dataWriter) {
Predicate<InputEvent> predicate,
BiConsumer<InputEvent, ControlData> dataWriter
) {
super(id); super(id);
this.packetId = NamespacedUtil.getId( this.packetId = NamespacedUtil.getId(NamespacedUtil.getNamespace(id),
NamespacedUtil.getNamespace(id), "ControlKeyPress" + NamespacedUtil.getName(id));
"ControlKeyPress" + NamespacedUtil.getName(id)
);
this.predicate = predicate; this.predicate = predicate;
this.dataWriter = dataWriter; this.dataWriter = dataWriter;
@ -54,10 +49,7 @@ public class ControlTriggerLambda extends ControlTriggerInputBased {
if (!predicate.test(event)) if (!predicate.test(event))
return null; return null;
PacketControl packet = new PacketControl( PacketControl packet = new PacketControl(packetId, ControlDataRegistry.getInstance().create(getId()));
packetId,
ControlDataRegistry.getInstance().create(getId())
);
dataWriter.accept(event, packet.getControl()); dataWriter.accept(event, packet.getControl());

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms.controls; package ru.windcorp.progressia.client.comms.controls;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -29,11 +29,7 @@ public class ControlTriggerLocalLambda extends ControlTriggerInputBased {
private final Predicate<InputEvent> predicate; private final Predicate<InputEvent> predicate;
private final Consumer<InputEvent> action; private final Consumer<InputEvent> action;
public ControlTriggerLocalLambda( public ControlTriggerLocalLambda(String id, Predicate<InputEvent> predicate, Consumer<InputEvent> action) {
String id,
Predicate<InputEvent> predicate,
Consumer<InputEvent> action
) {
super(id); super(id);
this.predicate = predicate; this.predicate = predicate;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms.controls; package ru.windcorp.progressia.client.comms.controls;
import ru.windcorp.progressia.common.util.namespaces.NamespacedInstanceRegistry; import ru.windcorp.progressia.common.util.namespaces.NamespacedInstanceRegistry;

View File

@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms.controls; package ru.windcorp.progressia.client.comms.controls;
import java.util.function.BiConsumer; import java.util.function.BiConsumer;
@ -27,216 +27,119 @@ import ru.windcorp.progressia.common.comms.controls.ControlData;
public class ControlTriggers { public class ControlTriggers {
public static ControlTriggerInputBased of( public static ControlTriggerInputBased of(String id, BiConsumer<InputEvent, ControlData> dataWriter,
String id, Predicate<InputEvent> predicate) {
BiConsumer<InputEvent, ControlData> dataWriter,
Predicate<InputEvent> predicate
) {
return new ControlTriggerLambda(id, predicate, dataWriter); return new ControlTriggerLambda(id, predicate, dataWriter);
} }
public static ControlTriggerInputBased of( public static ControlTriggerInputBased of(String id, Consumer<ControlData> dataWriter,
String id, Predicate<InputEvent> predicate) {
Consumer<ControlData> dataWriter, return of(id, (input, control) -> dataWriter.accept(control), predicate);
Predicate<InputEvent> predicate
) {
return of(
id,
(input, control) -> dataWriter.accept(control),
predicate
);
} }
public static ControlTriggerInputBased of( public static ControlTriggerInputBased of(String id, Predicate<InputEvent> predicate) {
String id, return of(id, (input, control) -> {
Predicate<InputEvent> predicate }, predicate);
) {
return of(
id,
(input, control) -> {
},
predicate
);
} }
@SafeVarargs @SafeVarargs
public static <I extends InputEvent> ControlTriggerInputBased of( public static <I extends InputEvent> ControlTriggerInputBased of(String id, Class<I> inputType,
String id, BiConsumer<I, ControlData> dataWriter, Predicate<I>... predicates) {
Class<I> inputType, return of(id, createCheckedDataWriter(inputType, dataWriter),
BiConsumer<I, ControlData> dataWriter, createCheckedCompoundPredicate(inputType, predicates));
Predicate<I>... predicates
) {
return of(
id,
createCheckedDataWriter(inputType, dataWriter),
createCheckedCompoundPredicate(inputType, predicates)
);
} }
@SafeVarargs @SafeVarargs
public static <I extends InputEvent> ControlTriggerInputBased of( public static <I extends InputEvent> ControlTriggerInputBased of(String id, Class<I> inputType,
String id, Consumer<ControlData> dataWriter, Predicate<I>... predicates) {
Class<I> inputType, return of(id, inputType, (input, control) -> dataWriter.accept(control), predicates);
Consumer<ControlData> dataWriter,
Predicate<I>... predicates
) {
return of(
id,
inputType,
(input, control) -> dataWriter.accept(control),
predicates
);
} }
@SafeVarargs @SafeVarargs
public static <I extends InputEvent> ControlTriggerInputBased of( public static <I extends InputEvent> ControlTriggerInputBased of(String id, Class<I> inputType,
String id, Predicate<I>... predicates) {
Class<I> inputType, return of(id, (input, control) -> {
Predicate<I>... predicates }, createCheckedCompoundPredicate(inputType, predicates));
) {
return of(
id,
(input, control) -> {
},
createCheckedCompoundPredicate(inputType, predicates)
);
} }
@SafeVarargs @SafeVarargs
public static ControlTriggerInputBased of( public static ControlTriggerInputBased of(String id, BiConsumer<InputEvent, ControlData> dataWriter,
String id, Predicate<InputEvent>... predicates) {
BiConsumer<InputEvent, ControlData> dataWriter, return of(id, InputEvent.class, dataWriter, predicates);
Predicate<InputEvent>... predicates
) {
return of(
id,
InputEvent.class,
dataWriter,
predicates
);
} }
@SafeVarargs @SafeVarargs
public static <I extends InputEvent> ControlTriggerInputBased of( public static <I extends InputEvent> ControlTriggerInputBased of(String id, Consumer<ControlData> dataWriter,
String id, Predicate<InputEvent>... predicates) {
Consumer<ControlData> dataWriter, return of(id, (input, control) -> dataWriter.accept(control), predicates);
Predicate<InputEvent>... predicates
) {
return of(
id,
(input, control) -> dataWriter.accept(control),
predicates
);
} }
@SafeVarargs @SafeVarargs
public static ControlTriggerInputBased of( public static ControlTriggerInputBased of(String id, Predicate<InputEvent>... predicates) {
String id, return of(id, InputEvent.class, (input, control) -> {
Predicate<InputEvent>... predicates }, predicates);
) {
return of(
id,
InputEvent.class,
(input, control) -> {
},
predicates
);
} }
public static ControlTriggerInputBased localOf( //
String id, //
Consumer<InputEvent> action, ///
Predicate<InputEvent> predicate ///
) { //
//
//
//
//
//
//
//
//
public static ControlTriggerInputBased localOf(String id, Consumer<InputEvent> action,
Predicate<InputEvent> predicate) {
return new ControlTriggerLocalLambda(id, predicate, action); return new ControlTriggerLocalLambda(id, predicate, action);
} }
public static ControlTriggerInputBased localOf( public static ControlTriggerInputBased localOf(String id, Runnable action, Predicate<InputEvent> predicate) {
String id, return localOf(id, input -> action.run(), predicate);
Runnable action,
Predicate<InputEvent> predicate
) {
return localOf(
id,
input -> action.run(),
predicate
);
} }
@SafeVarargs @SafeVarargs
public static <I extends InputEvent> ControlTriggerInputBased localOf( public static <I extends InputEvent> ControlTriggerInputBased localOf(String id, Class<I> inputType,
String id, Consumer<I> action, Predicate<I>... predicates) {
Class<I> inputType, return localOf(id, createCheckedAction(inputType, action),
Consumer<I> action, createCheckedCompoundPredicate(inputType, predicates));
Predicate<I>... predicates
) {
return localOf(
id,
createCheckedAction(inputType, action),
createCheckedCompoundPredicate(inputType, predicates)
);
} }
@SafeVarargs @SafeVarargs
public static <I extends InputEvent> ControlTriggerInputBased localOf( public static <I extends InputEvent> ControlTriggerInputBased localOf(String id, Class<I> inputType,
String id, Runnable action, Predicate<I>... predicates) {
Class<I> inputType, return localOf(id, inputType, input -> action.run(), predicates);
Runnable action,
Predicate<I>... predicates
) {
return localOf(
id,
inputType,
input -> action.run(),
predicates
);
} }
@SafeVarargs @SafeVarargs
public static ControlTriggerInputBased localOf( public static ControlTriggerInputBased localOf(String id, Consumer<InputEvent> action,
String id, Predicate<InputEvent>... predicates) {
Consumer<InputEvent> action, return localOf(id, InputEvent.class, action, predicates);
Predicate<InputEvent>... predicates
) {
return localOf(
id,
InputEvent.class,
action,
predicates
);
} }
@SafeVarargs @SafeVarargs
public static <I extends InputEvent> ControlTriggerInputBased localOf( public static <I extends InputEvent> ControlTriggerInputBased localOf(String id, Runnable action,
String id, Predicate<InputEvent>... predicates) {
Runnable action, return of(id, input -> action.run(), predicates);
Predicate<InputEvent>... predicates
) {
return of(
id,
input -> action.run(),
predicates
);
} }
private static <I extends InputEvent> BiConsumer<InputEvent, ControlData> createCheckedDataWriter( private static <I extends InputEvent> BiConsumer<InputEvent, ControlData> createCheckedDataWriter(
Class<I> inputType, Class<I> inputType, BiConsumer<I, ControlData> dataWriter) {
BiConsumer<I, ControlData> dataWriter
) {
return (inputEvent, control) -> dataWriter.accept(inputType.cast(inputEvent), control); return (inputEvent, control) -> dataWriter.accept(inputType.cast(inputEvent), control);
} }
private static <I extends InputEvent> Consumer<InputEvent> createCheckedAction( private static <I extends InputEvent> Consumer<InputEvent> createCheckedAction(Class<I> inputType,
Class<I> inputType, Consumer<I> action) {
Consumer<I> action
) {
return inputEvent -> action.accept(inputType.cast(inputEvent)); return inputEvent -> action.accept(inputType.cast(inputEvent));
} }
private static <I extends InputEvent> Predicate<InputEvent> createCheckedCompoundPredicate( private static <I extends InputEvent> Predicate<InputEvent> createCheckedCompoundPredicate(Class<I> inputType,
Class<I> inputType, Predicate<I>[] predicates) {
Predicate<I>[] predicates
) {
return new CompoundCastPredicate<>(inputType, predicates); return new CompoundCastPredicate<>(inputType, predicates);
} }

View File

@ -15,11 +15,11 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package ru.windcorp.progressia.client.comms.controls; package ru.windcorp.progressia.client.comms.controls;
import ru.windcorp.progressia.client.Client; import ru.windcorp.progressia.client.Client;
import ru.windcorp.progressia.client.graphics.input.InputEvent; import ru.windcorp.progressia.client.graphics.input.bus.Input;
import ru.windcorp.progressia.common.comms.packets.Packet; import ru.windcorp.progressia.common.comms.packets.Packet;
public class InputBasedControls { public class InputBasedControls {
@ -32,16 +32,15 @@ public class InputBasedControls {
this.client = client; this.client = client;
this.controls = ControlTriggerRegistry.getInstance().values().stream() this.controls = ControlTriggerRegistry.getInstance().values().stream()
.filter(ControlTriggerInputBased.class::isInstance) .filter(ControlTriggerInputBased.class::isInstance).toArray(ControlTriggerInputBased[]::new);
.toArray(ControlTriggerInputBased[]::new);
} }
public void handleInput(InputEvent event) { public void handleInput(Input input) {
for (ControlTriggerInputBased c : controls) { for (ControlTriggerInputBased c : controls) {
Packet packet = c.onInputEvent(event); Packet packet = c.onInputEvent(input.getEvent());
if (packet != null) { if (packet != null) {
event.consume(); input.consume();
client.getComms().sendPacket(packet); client.getComms().sendPacket(packet);
break; break;
} }

View File

@ -21,7 +21,6 @@ package ru.windcorp.progressia.client.comms.localhost;
import ru.windcorp.progressia.client.comms.ServerCommsChannel; import ru.windcorp.progressia.client.comms.ServerCommsChannel;
import ru.windcorp.progressia.common.comms.packets.Packet; import ru.windcorp.progressia.common.comms.packets.Packet;
import ru.windcorp.progressia.server.Server; import ru.windcorp.progressia.server.Server;
import ru.windcorp.progressia.server.ServerState;
public class LocalServerCommsChannel extends ServerCommsChannel { public class LocalServerCommsChannel extends ServerCommsChannel {
@ -35,11 +34,7 @@ public class LocalServerCommsChannel extends ServerCommsChannel {
public void connect(String login) { public void connect(String login) {
setState(State.CONNECTED); setState(State.CONNECTED);
this.localClient = new LocalClient( this.localClient = new LocalClient(server.getClientManager().grabClientId(), login, this);
server.getClientManager().grabClientId(),
login,
this
);
server.getClientManager().addClient(localClient); server.getClientManager().addClient(localClient);
} }
@ -55,7 +50,7 @@ public class LocalServerCommsChannel extends ServerCommsChannel {
@Override @Override
public void disconnect() { public void disconnect() {
ServerState.getInstance().getClientManager().disconnectClient(localClient); // Do nothing
} }
} }

View File

@ -34,7 +34,13 @@ public class Colors {
DEBUG_BLUE = toVector(0xFF0000FF), DEBUG_BLUE = toVector(0xFF0000FF),
DEBUG_CYAN = toVector(0xFF00FFFF), DEBUG_CYAN = toVector(0xFF00FFFF),
DEBUG_MAGENTA = toVector(0xFFFF00FF), DEBUG_MAGENTA = toVector(0xFFFF00FF),
DEBUG_YELLOW = toVector(0xFFFFFF00); DEBUG_YELLOW = toVector(0xFFFFFF00),
LIGHT_GRAY = toVector(0xFFCBCBD0),
BLUE = toVector(0xFF37A2E6),
HOVER_BLUE = toVector(0xFFC3E4F7),
DISABLED_GRAY = toVector(0xFFE5E5E5),
DISABLED_BLUE = toVector(0xFFB2D8ED);
public static Vec4 toVector(int argb) { public static Vec4 toVector(int argb) {
return toVector(argb, new Vec4()); return toVector(argb, new Vec4());

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