Repository: rafaskb/typing-label
Branch: master
Commit: c783d41e9867
Files: 48
Total size: 211.0 KB
Directory structure:
gitextract_7_7qo6u8/
├── .gitignore
├── CHANGES
├── LICENSE
├── README.md
├── build.gradle
├── eclipse-formatter.xml
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── jitpack.yml
└── src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── rafaskoberg/
│ │ └── gdx/
│ │ └── typinglabel/
│ │ ├── Effect.java
│ │ ├── GlyphUtils.java
│ │ ├── InternalToken.java
│ │ ├── Parser.java
│ │ ├── TokenCategory.java
│ │ ├── TokenDelimiter.java
│ │ ├── TokenEntry.java
│ │ ├── TypingAdapter.java
│ │ ├── TypingConfig.java
│ │ ├── TypingGlyph.java
│ │ ├── TypingLabel.java
│ │ ├── TypingListener.java
│ │ ├── effects/
│ │ │ ├── BlinkEffect.java
│ │ │ ├── EaseEffect.java
│ │ │ ├── FadeEffect.java
│ │ │ ├── GradientEffect.java
│ │ │ ├── HangEffect.java
│ │ │ ├── JumpEffect.java
│ │ │ ├── RainbowEffect.java
│ │ │ ├── ShakeEffect.java
│ │ │ ├── SickEffect.java
│ │ │ ├── SlideEffect.java
│ │ │ ├── WaveEffect.java
│ │ │ └── WindEffect.java
│ │ └── utils/
│ │ ├── ColorUtils.java
│ │ └── SimplexNoise.java
│ └── resources/
│ └── com/
│ └── rafaskoberg/
│ └── gdx/
│ └── typinglabel/
│ └── typinglabel.gwt.xml
└── test/
├── java/
│ └── com/
│ └── rafaskoberg/
│ └── gdx/
│ └── typinglabel/
│ └── TypingLabelTest.java
└── resources/
├── arial18.fnt
├── default.fnt
├── text/
│ ├── colors.txt
│ ├── default.txt
│ ├── gender_pronouns.txt
│ └── gender_pronouns_defaults.txt
├── uiskin.atlas
└── uiskin.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
## Java
*.class
*.war
*.ear
hs_err_pid*
replay_pid*
## GWT
war/
html/war/gwt_bree/
html/gwt-unitCache/
.apt_generated/
html/war/WEB-INF/deploy/
html/war/WEB-INF/classes/
.gwt/
gwt-unitCache/
www-test/
.gwt-tmp/
## Android Studio and Intellij and Android in general
android/libs/armeabi/
android/libs/armeabi-v7a/
android/libs/x86/
android/gen/
.idea/
*.ipr
*.iws
*.iml
out/
com_crashlytics_export_strings.xml
## Eclipse
.classpath
.project
.metadata
**/bin/
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.externalToolBuilders/
*.launch
## NetBeans
**/nbproject/private/
build/
nbbuild/
dist/
nbdist/
nbactions.xml
nb-configuration.xml
## Gradle
.gradle
build/
## OS Specific
.DS_Store
docs/
================================================
FILE: CHANGES
================================================
[Unreleased]
- Nothing here so far.
[1.4.0]
- BREAKING CHANGE: Added support for multiple TypingListeners in TypingLabel. Methods "getTypingListener" and "getTypingListeners" were replaced by "setTypingListener" and "addTypingListener".
- Added If Conditionals! {IF=GENDER;f=She;m=He;t=Them;Unknown} -- See details in the wiki.
- Updated Regexodus dependency for GWT. If you use GWT and inherit Regexodus in your project, follow the installation instructions again, as some of them have changed (namely the `inherits` line).
- Fixed color tags being applied to the incorrect glyph indices. Thanks @tommyettinger!
- Fixed alpha not being applied to glyphs not affected by color-altering tokens. Thanks @tommyettinger!
[1.3.0]
- Fixed Windows line breaks (CR/LF) causing effect tokens to skip characters. This was mostly noticeable when loading strings from a text file.
- Added `TokenDelimiter` configuration to `TypingConfig`, allowing users to change the token syntax. {CurlyBrackets}, [Brackets], and (Parentheses) are supported.
- TypingLabel now depends on libGDX 1.11.0, because of differences in how it handles text internally (which this depends on). If you need compatibility with libGDX 1.9.9 through 1.10.0, you must use version 1.2.0 at the latest.
[1.2.0]
- API Addition: Added isSkipping method to TypingLabel class.
- Fixed exception being thrown when parsing malformed color values from token arguments.
- Fixed longer texts not being processed correctly after a setText call. Labels will now restart automatically after a setText call and will also skip to the end in case their progression has already ended.
- Fixed issue causing labels not to align properly to the X axis.
- Fixed some issues related to extreme frame rates, both high and low. Now the effects should remain the same independent of the FPS.
- Fixed color tokens not detecting hex codes without a hash character.
- Added new SLIDE effect.
- Added new HANG effect.
[1.1.0]
- Added global variables that can be set in TypingConfig.GLOBAL_VARS.
- API Change: Effect::onApply now takes a TypingGlyph instead of Glyph. This might break custom effects.
- Added new RAINBOW effect.
- Added new GRADIENT effect.
- Added new FADE effect.
- Added new BLINK effect.
- Added ENDCOLOR token, an alias of CLEARCOLOR, to be consistent with the rest of the tokens.
[1.0.7]
- Added new WIND effect.
- Added proper support to HTML / GWT by using RegExodus, thanks tommyettinger! See https://github.com/rafaskb/typing-label/pull/12
[1.0.6]
- Fixed bug causing glyphs to appear completely out of place.
[1.0.5]
- Added new SICK effect.
- Fixed nasty bug causing effects to affect the wrong glyphs after line breaks due to line wraps not being accounted for.
- Added support for custom effect tokens.
- API Addition: Added registerEffect and unregisterEffect methods to TypingConfig.
[1.0.4]
- Fixed bug causing last glyph to be rendered as the first one in some cases.
[1.0.3]
- API Addition: Notify listener about character progression through the method onChar(Character).
- API Addition: Added cancelSkipping(), which can be called during events after skipToTheEnd() is called.
- Fixed variables not being replaced without having a listener set.
- Fixed exception when using null as text.
[1.0.2]
- Added a way to replace variables through a listener method, instead of having to provide fixed values.
- Effect tokens now end previous effects of the same type, to prevent similar effects to stack.
- Dispose cached glyphs when label is removed from its parent.
- Fixed bug causing restart() to not actually restart the text when called from listener.end().
- Fixed bug causing weird effects to glyphs, especially on wrapped labels.
- Fixed text effects ending at the wrong character.
- Fixed events being fired at the wrong character.
[1.0.1]
- Added option to ignore events and effects while skipping to the end.
- Fixed exception being thrown when the text reached the end.
- Fixed {WAIT} tokens pausing the text one glyph ahead its position.
- Fixed TypingLabel.end() being called too many times.
- Forced all labels to calculate their full layouts. This fixes a bug causing one-line labels to not being rendered at all.
- Fixed error when creating an empty label.
[1.0.0]
- Initial code
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017 Rafael Skoberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================

# TypingLabel
[](https://search.maven.org/#search%7Cga%7C1%7Ca%3A%22typing-label%22)
[](https://github.com/rafaskb/typing-label/blob/master/LICENSE)
A libGDX Label that appears as if it was being typed in real time.
It works as a drop-in replacement for normal [Scene2D Labels](https://libgdx.com/wiki/graphics/2d/scene2d/scene2d-ui#label), and you can use optional [tokens](https://github.com/rafaskb/typing-label/wiki/Tokens) to customize the text's behavior.

## Installation
Open _build.gradle_ in project root and add this to the _ext_ section under _allprojects_:
```groovy
typingLabelVersion = '1.4.0'
regExodusVersion = '0.1.13' // Only if you're using HTML / GWT
```
#### Core module
Add this to your _build.gradle_ core dependencies:
```groovy
api "com.rafaskoberg.gdx:typing-label:$typingLabelVersion"
```
> _Note: Replace `api` with `compile` if you're using a Gradle version older than 3.4._
#### HTML dependencies
###### (Only if you're using HTML / GWT)
Add this to your _GdxDefinition.gwt.xml_ file:
```xml
```
Add this to your _build.gradle_ html dependencies:
```groovy
api "com.github.tommyettinger:regexodus:$regExodusVersion:sources"
api "com.rafaskoberg.gdx:typing-label:$typingLabelVersion:sources"
```
> _Note: Replace `api` with `compile` if you're using a Gradle version older than 3.4._
## Getting Started
Check the Wiki:
- [Usage examples](https://github.com/rafaskb/typing-label/wiki/Examples)
- [Tokens](https://github.com/rafaskb/typing-label/wiki/Tokens)
- [Fine tuning](https://github.com/rafaskb/typing-label/wiki/Fine-Tuning)
- [Custom Effects](https://github.com/rafaskb/typing-label/wiki/Tokens#custom-effects)
## textratypist and SDF / MSDF Support
_Multi-channel Signed Distance Field_ fonts allow you to prepare and load just one font file and render it in any scale you want, while mantaining the quality and cripsness of the original texture, as if you were working directly with vectors.
Since TypingLabel aims to be a replacement for regular scene2d.ui Labels though, that means it relies on BitmapFonts, which have a specific size and don't work well with scaling.
If you're using SDF fonts in your project and want TypingLabel features, then make sure to take a look at [Textramode](https://github.com/tommyettinger/textramode) and [Textratypist](https://github.com/tommyettinger/textramode) libraries by [Tommy Ettinger](https://github.com/tommyettinger). They support SDF and MSDF fonts, have much of the TypingLabel features, as well extended markup such as bold and oblique, and much more.
================================================
FILE: build.gradle
================================================
buildscript {
repositories {
mavenLocal()
mavenCentral()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
gradlePluginPortal()
}
dependencies {
classpath 'com.vanniktech:gradle-maven-publish-plugin:0.17.0'
}
}
apply plugin: 'java-library'
apply plugin: 'com.vanniktech.maven.publish'
sourceCompatibility = 1.7
def projectName = 'typing-label'
version "$VERSION_NAME"
group 'com.rafaskoberg.gdx'
[compileJava, compileTestJava, javadoc]*.options*.encoding = 'UTF-8'
// Disable JDK 8's doclint
// http://blog.joda.org/2014/02/turning-off-doclint-in-jdk-8-javadoc.html
if (JavaVersion.current().isJava8Compatible()) {
allprojects {
tasks.withType(Javadoc) {
// The -quiet is because of some sort of weird JDK JavaCompiler bug:
// https://discuss.gradle.org/t/passing-arguments-to-compiler-and-javadoc/1661
options.addStringOption('Xdoclint:none,-missing', '-quiet')
}
}
}
if(JavaVersion.current().isJava9Compatible()) {
allprojects {
tasks.withType(JavaCompile) {
options.release.set(7)
}
}
}
sourceSets.test.resources.srcDirs = [ file('src/test/resources').path ]
javadoc.destinationDir = file('docs/apidocs')
jar {
duplicatesStrategy(DuplicatesStrategy.EXCLUDE)
archiveBaseName.set(projectName)
manifest {
attributes 'Implementation-Title': projectName, 'Implementation-Version': archiveVersion
}
}
repositories {
mavenCentral()
maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}
dependencies {
api group: 'com.badlogicgames.gdx', name: 'gdx', version: gdxVersion
api group: 'com.github.tommyettinger', name: 'regexodus', version: regExodusVersion
testImplementation group: 'com.badlogicgames.gdx', name: 'gdx-backend-lwjgl', version: gdxVersion
testImplementation group: 'com.badlogicgames.gdx', name: 'gdx-platform', version: gdxVersion, classifier: 'natives-desktop'
}
================================================
FILE: eclipse-formatter.xml
================================================
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
================================================
FILE: gradle.properties
================================================
org.gradle.daemon=true
org.gradle.jvmargs=-Xms128m -Xmx512m -Dfile.encoding=UTF-8 -Dconsole.encoding=UTF-8
org.gradle.configureondemand=false
gdxVersion=1.11.0
regExodusVersion=0.1.15
GROUP=com.rafaskoberg.gdx
POM_ARTIFACT_ID=typing-label
VERSION_NAME=1.4.1-SNAPSHOT
POM_NAME=typing-label
POM_DESCRIPTION=A libGDX Label that appears as if it was being typed in real time.
POM_INCEPTION_YEAR=2017
POM_URL=https://github.com/rafaskb/typing-label/
POM_SCM_URL=https://github.com/rafaskb/typing-label/
POM_SCM_CONNECTION=scm:https://rafaskb@github.com/rafaskb/typing-label.git
POM_SCM_DEV_CONNECTION=scm:git://github.com/rafaskb/typing-label.git
POM_LICENCE_NAME=The MIT License (MIT)
POM_LICENCE_URL=https://mit-license.org/
POM_LICENCE_DIST=repo
POM_DEVELOPER_ID=rafaskb
POM_DEVELOPER_NAME=Rafa Skoberg
POM_DEVELOPER_URL=https://github.com/rafaskb/
POM_DEVELOPER_EMAIL=rafa.skoberg@gmail.com
================================================
FILE: gradlew
================================================
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
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.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
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`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
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
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
================================================
FILE: gradlew.bat
================================================
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
: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
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: jitpack.yml
================================================
jdk:
- openjdk16
install:
- echo "Installing with Gradle"
- chmod 755 gradlew
- ./gradlew clean publishToMavenLocal -x signMavenPublication
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/Effect.java
================================================
package com.rafaskoberg.gdx.typinglabel;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
/** Abstract text effect. */
public abstract class Effect {
private static final float FADEOUT_SPLIT = 0.25f;
protected final TypingLabel label;
public int indexStart = -1;
public int indexEnd = -1;
public float duration = Float.POSITIVE_INFINITY;
protected float totalTime;
public Effect(TypingLabel label) {
this.label = label;
}
public void update(float delta) {
totalTime += delta;
}
/** Applies the effect to the given glyph. */
public final void apply(TypingGlyph glyph, int glyphIndex, float delta) {
int localIndex = glyphIndex - indexStart;
onApply(glyph, localIndex, delta);
}
/** Called when this effect should be applied to the given glyph. */
protected abstract void onApply(TypingGlyph glyph, int localIndex, float delta);
/** Returns whether or not this effect is finished and should be removed. Note that effects are infinite by default. */
public boolean isFinished() {
return totalTime > duration;
}
/** Calculates the fadeout of this effect, if any. Only considers the second half of the duration. */
protected float calculateFadeout() {
if(Float.isInfinite(duration)) return 1;
// Calculate raw progress
float progress = MathUtils.clamp(totalTime / duration, 0, 1);
// If progress is before the split point, return a full factor
if(progress < FADEOUT_SPLIT) return 1;
// Otherwise calculate from the split point
return Interpolation.smooth.apply(1, 0, (progress - FADEOUT_SPLIT) / (1f - FADEOUT_SPLIT));
}
/**
* Calculates a linear progress dividing the total time by the given modifier. Returns a value between 0 and 1 that
* loops in a ping-pong mode.
*/
protected float calculateProgress(float modifier) {
return calculateProgress(modifier, 0, true);
}
/**
* Calculates a linear progress dividing the total time by the given modifier. Returns a value between 0 and 1 that
* loops in a ping-pong mode.
*/
protected float calculateProgress(float modifier, float offset) {
return calculateProgress(modifier, offset, true);
}
/** Calculates a linear progress dividing the total time by the given modifier. Returns a value between 0 and 1. */
protected float calculateProgress(float modifier, float offset, boolean pingpong) {
float progress = totalTime / modifier + offset;
while(progress < 0.0f) {
progress += 2.0f;
}
if(pingpong) {
progress %= 2f;
if(progress > 1.0f) progress = 1f - (progress - 1f);
} else {
progress %= 1.0f;
}
progress = MathUtils.clamp(progress, 0, 1);
return progress;
}
/** Returns the line height of the label controlling this effect. */
protected float getLineHeight() {
return label.getBitmapFontCache().getFont().getLineHeight() * label.getFontScaleY();
}
/** Returns a float value parsed from the given String, or the default value if the string couldn't be parsed. */
protected float paramAsFloat(String str, float defaultValue) {
return Parser.stringToFloat(str, defaultValue);
}
/** Returns a boolean value parsed from the given String, or the default value if the string couldn't be parsed. */
protected boolean paramAsBoolean(String str) {
return Parser.stringToBoolean(str);
}
/** Parses a color from the given string. Returns null if the color couldn't be parsed. */
protected Color paramAsColor(String str) {
return Parser.stringToColor(str);
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/GlyphUtils.java
================================================
package com.rafaskoberg.gdx.typinglabel;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
import com.badlogic.gdx.utils.ReflectionPool;
/** Utility class to manage {@link Glyph} pooling and cloning. */
class GlyphUtils {
private static final Pool pool = new ReflectionPool(TypingGlyph.class) {
protected void reset(TypingGlyph glyph) {
GlyphUtils.reset(glyph);
}
};
/**
* Returns a glyph from this pool. The glyph may be new (from {@link Pool#newObject()}) or reused (previously {@link
* Pool#free(Object) freed}).
*/
static TypingGlyph obtain() {
return pool.obtain();
}
/**
* Returns a glyph from this pool and clones it from the given one. The glyph may be new (from {@link
* Pool#newObject()}) or reused (previously {@link Pool#free(Object) freed}).
*/
static Glyph obtainClone(Glyph from) {
TypingGlyph glyph = pool.obtain();
clone(from, glyph);
return glyph;
}
/**
* Puts the specified glyph in the pool, making it eligible to be returned by {@link #obtain()}. If the pool already
* contains {@link Pool#max} free glyphs, the specified glyph is reset but not added to the pool.
*/
static void free(TypingGlyph glyph) {
pool.free(glyph);
}
/**
* Puts the specified glyphs in the pool. Null glyphs within the array are silently ignored.
*
* @see Pool#free(Object)
*/
static void freeAll(Array glyphs) {
pool.freeAll(glyphs);
}
/** Called when a glyph is freed to clear the state of the glyph for possible later reuse. */
static void reset(TypingGlyph glyph) {
glyph.id = 0;
glyph.srcX = 0;
glyph.srcY = 0;
glyph.width = 0;
glyph.height = 0;
glyph.u = 0;
glyph.v = 0;
glyph.u2 = 0;
glyph.v2 = 0;
glyph.xoffset = 0;
glyph.yoffset = 0;
glyph.xadvance = 0;
glyph.kerning = null;
glyph.fixedWidth = false;
glyph.runColor = 0xFFFFFFFF;
glyph.internalIndex = -1;
glyph.color = null;
}
/** Copies all contents from the first glyph to the second one. */
static void clone(Glyph from, TypingGlyph to) {
to.id = from.id;
to.srcX = from.srcX;
to.srcY = from.srcY;
to.width = from.width;
to.height = from.height;
to.u = from.u;
to.v = from.v;
to.u2 = from.u2;
to.v2 = from.v2;
to.xoffset = from.xoffset;
to.yoffset = from.yoffset;
to.xadvance = from.xadvance;
to.kerning = from.kerning; // Keep the same instance, there's no reason to deep clone it
to.fixedWidth = from.fixedWidth;
to.runColor = 0xFFFFFFFF;
to.internalIndex = -1;
to.color = null;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/InternalToken.java
================================================
package com.rafaskoberg.gdx.typinglabel;
enum InternalToken {
// @formatter:off
// Public
WAIT ("WAIT", TokenCategory.WAIT ),
SPEED ("SPEED", TokenCategory.SPEED ),
SLOWER ("SLOWER", TokenCategory.SPEED ),
SLOW ("SLOW", TokenCategory.SPEED ),
NORMAL ("NORMAL", TokenCategory.SPEED ),
FAST ("FAST", TokenCategory.SPEED ),
FASTER ("FASTER", TokenCategory.SPEED ),
COLOR ("COLOR", TokenCategory.COLOR ),
CLEARCOLOR ("CLEARCOLOR", TokenCategory.COLOR ),
ENDCOLOR ("ENDCOLOR", TokenCategory.COLOR ),
VAR ("VAR", TokenCategory.VARIABLE ),
IF ("IF", TokenCategory.IF ),
EVENT ("EVENT", TokenCategory.EVENT ),
RESET ("RESET", TokenCategory.RESET ),
SKIP ("SKIP", TokenCategory.SKIP );
// @formatter:on
final String name;
final TokenCategory category;
private InternalToken(String name, TokenCategory category) {
this.name = name;
this.category = category;
}
@Override
public String toString() {
return name;
}
static InternalToken fromName(String name) {
if(name != null) {
for(InternalToken token : values()) {
if(name.equalsIgnoreCase(token.name)) {
return token;
}
}
}
return null;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/Parser.java
================================================
package com.rafaskoberg.gdx.typinglabel;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Colors;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.reflect.ClassReflection;
import com.badlogic.gdx.utils.reflect.Constructor;
import com.badlogic.gdx.utils.reflect.ReflectionException;
import regexodus.Matcher;
import regexodus.Pattern;
import regexodus.REFlags;
/** Utility class to parse tokens from a {@link TypingLabel}. */
class Parser {
private static TokenDelimiter CURRENT_DELIMITER = TypingConfig.TOKEN_DELIMITER;
private static Pattern PATTERN_TOKEN_STRIP = compileTokenPattern();
private static Pattern PATTERN_MARKUP_STRIP = Pattern.compile("(\\[{2})|(\\[#?\\w*(\\[|\\])?)");
private static final Pattern PATTERN_COLOR_HEX_NO_HASH = Pattern.compile("[A-F0-9]{6}");
private static final String[] BOOLEAN_TRUE = {"true", "yes", "t", "y", "on", "1"};
private static final int INDEX_TOKEN = 1;
private static final int INDEX_PARAM = 2;
private static String RESET_REPLACEMENT;
/** Parses all tokens from the given {@link TypingLabel}. */
static void parseTokens(TypingLabel label) {
// Detect if token delimiter has changed
boolean hasDelimiterChanged = CURRENT_DELIMITER != TypingConfig.TOKEN_DELIMITER;
if(hasDelimiterChanged) {
CURRENT_DELIMITER = TypingConfig.TOKEN_DELIMITER;
}
// Compile patterns if necessary
if(PATTERN_TOKEN_STRIP == null || TypingConfig.dirtyEffectMaps || hasDelimiterChanged) {
PATTERN_TOKEN_STRIP = compileTokenPattern();
}
if(RESET_REPLACEMENT == null || TypingConfig.dirtyEffectMaps || hasDelimiterChanged) {
RESET_REPLACEMENT = getResetReplacement();
}
// Adjust and check markup color
if(label.forceMarkupColor) label.getBitmapFontCache().getFont().getData().markupEnabled = true;
// Remove any previous entries
label.tokenEntries.clear();
// Parse all tokens with text replacements, namely color and var.
parseReplacements(label);
// Parse all regular tokens and properly register them
parseRegularTokens(label);
// Parse color markups and register SKIP tokens
parseColorMarkups(label);
// Sort token entries
label.tokenEntries.sort();
label.tokenEntries.reverse();
}
/** Parse tokens that only replace text, such as colors and variables. */
private static void parseReplacements(TypingLabel label) {
// Get text
CharSequence text = label.getText();
boolean hasMarkup = label.getBitmapFontCache().getFont().getData().markupEnabled;
// Create string builder
StringBuilder sb = new StringBuilder(text.length());
Matcher m = PATTERN_TOKEN_STRIP.matcher(text);
int matcherIndexOffset = 0;
// Iterate through matches
while(true) {
// Reset StringBuilder and matcher
sb.setLength(0);
m.setTarget(text);
m.setPosition(matcherIndexOffset);
// Make sure there's at least one regex match
if(!m.find()) break;
// Get token and parameter
final InternalToken internalToken = InternalToken.fromName(m.group(INDEX_TOKEN));
final String param = m.group(INDEX_PARAM);
// If token couldn't be parsed, move one index forward to continue the search
if(internalToken == null) {
matcherIndexOffset++;
continue;
}
// Process tokens and handle replacement
String replacement = "";
switch(internalToken) {
case COLOR:
if(hasMarkup) replacement = stringToColorMarkup(param);
break;
case ENDCOLOR:
case CLEARCOLOR:
if(hasMarkup) replacement = "[#" + label.getClearColor().toString() + "]";
break;
case VAR:
replacement = null;
// Try to replace variable through listeners.
for(TypingListener listener : label.getTypingListeners()) {
replacement = listener.replaceVariable(param);
if(replacement != null) break;
}
// If replacement is null, get value from maps.
if(replacement == null) {
replacement = label.getVariables().get(param.toUpperCase());
}
// If replacement is still null, get value from global scope
if(replacement == null) {
replacement = TypingConfig.GLOBAL_VARS.get(param.toUpperCase());
}
// Make sure we're not inserting "null" to the text.
if(replacement == null) replacement = param.toUpperCase();
break;
case IF:
// Process token
replacement = processIfToken(label, param);
// Make sure we're not inserting "null" to the text.
if(replacement == null) replacement = param.toUpperCase();
break;
case RESET:
replacement = RESET_REPLACEMENT + label.getDefaultToken();
break;
default:
// We don't want to process this token now. Move one index forward to continue the search
matcherIndexOffset++;
continue;
}
// Update text with replacement
m.setPosition(m.start());
text = m.replaceFirst(replacement);
}
// Set new text
label.setText(text, false, false);
}
private static String processIfToken(TypingLabel label, String paramsString) {
// Split params
final String[] params = paramsString == null ? new String[0] : paramsString.split(";");
final String variable = params.length > 0 ? params[0] : null;
// Ensure our params are valid
if(params.length <= 1 || variable == null) {
return null;
}
/*
Get variable's value
*/
String variableValue = null;
// Try to get value through listener.
for(TypingListener listener : label.getTypingListeners()) {
variableValue = listener.replaceVariable(variable);
if(variableValue != null) break;
}
// If value is null, get it from maps.
if(variableValue == null) {
variableValue = label.getVariables().get(variable.toUpperCase());
}
// If value is still null, get it from global scope
if(variableValue == null) {
variableValue = TypingConfig.GLOBAL_VARS.get(variable.toUpperCase());
}
// Ensure variable is never null
if(variableValue == null) {
variableValue = "";
}
// Iterate through params and try to find a match
String defaultValue = null;
for(int i = 1, n = params.length; i < n; i++) {
String[] subParams = params[i].split("=", 2);
String key = subParams[0];
String value = subParams[subParams.length - 1];
boolean isKeyValid = subParams.length > 1 && !key.isEmpty();
// If key isn't valid, it must be a default value. Store it and carry on
if(!isKeyValid) {
defaultValue = value;
break;
}
// Compare variable's value with key
if(variableValue.equalsIgnoreCase(key)) {
return value;
}
}
// Try to return any default values captured during the iteration
if(defaultValue != null) {
return defaultValue;
}
// If we got this far, no values matched our variable.
// Return the variable itself, which might be useful for debugging.
return variable;
}
/** Parses regular tokens that don't need replacement and register their indexes in the {@link TypingLabel}. */
private static void parseRegularTokens(TypingLabel label) {
// Get text
CharSequence text = label.getText();
// Create matcher and StringBuilder
Matcher m = PATTERN_TOKEN_STRIP.matcher(text);
StringBuilder sb = new StringBuilder(text.length());
int matcherIndexOffset = 0;
// Iterate through matches
while(true) {
// Reset matcher and StringBuilder
m.setTarget(text);
sb.setLength(0);
m.setPosition(matcherIndexOffset);
// Make sure there's at least one regex match
if(!m.find()) break;
// Get token name and category
String tokenName = m.group(INDEX_TOKEN).toUpperCase();
TokenCategory tokenCategory = null;
InternalToken tmpToken = InternalToken.fromName(tokenName);
if(tmpToken == null) {
if(TypingConfig.EFFECT_START_TOKENS.containsKey(tokenName)) {
tokenCategory = TokenCategory.EFFECT_START;
} else if(TypingConfig.EFFECT_END_TOKENS.containsKey(tokenName)) {
tokenCategory = TokenCategory.EFFECT_END;
}
} else {
tokenCategory = tmpToken.category;
}
// Get token, param and index of where the token begins
int groupCount = m.groupCount();
final String paramsString = groupCount == INDEX_PARAM ? m.group(INDEX_PARAM) : null;
final String[] params = paramsString == null ? new String[0] : paramsString.split(";");
final String firstParam = params.length > 0 ? params[0] : null;
final int index = m.start(0);
int indexOffset = 0;
// If token couldn't be parsed, move one index forward to continue the search
if(tokenCategory == null) {
matcherIndexOffset++;
continue;
}
// Process tokens
float floatValue = 0;
String stringValue = null;
Effect effect = null;
switch(tokenCategory) {
case WAIT: {
floatValue = stringToFloat(firstParam, TypingConfig.DEFAULT_WAIT_VALUE);
break;
}
case EVENT: {
stringValue = paramsString;
indexOffset = -1;
break;
}
case SPEED: {
switch(tokenName) {
case "SPEED":
float minModifier = TypingConfig.MIN_SPEED_MODIFIER;
float maxModifier = TypingConfig.MAX_SPEED_MODIFIER;
float modifier = MathUtils.clamp(stringToFloat(firstParam, 1), minModifier, maxModifier);
floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / modifier;
break;
case "SLOWER":
floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 0.500f;
break;
case "SLOW":
floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 0.667f;
break;
case "NORMAL":
floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR;
break;
case "FAST":
floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 2.000f;
break;
case "FASTER":
floatValue = TypingConfig.DEFAULT_SPEED_PER_CHAR / 4.000f;
break;
}
break;
}
case EFFECT_START: {
Class extends Effect> clazz = TypingConfig.EFFECT_START_TOKENS.get(tokenName.toUpperCase());
try {
if(clazz != null) {
Constructor constructor = ClassReflection.getConstructors(clazz)[0];
int constructorParamCount = constructor.getParameterTypes().length;
if(constructorParamCount >= 2) {
effect = (Effect) constructor.newInstance(label, params);
} else {
effect = (Effect) constructor.newInstance(label);
}
}
} catch(ReflectionException e) {
String message = "Failed to initialize " + tokenName + " effect token. Make sure the associated class (" + clazz + ") has only one constructor with TypingLabel as first parameter and optionally String[] as second.";
throw new IllegalStateException(message, e);
}
break;
}
case EFFECT_END: {
break;
}
}
// Register token
TokenEntry entry = new TokenEntry(tokenName, tokenCategory, index + indexOffset, floatValue, stringValue);
entry.effect = effect;
label.tokenEntries.add(entry);
// Set new text without tokens
m.setPosition(0);
text = m.replaceFirst("");
}
// Update label text
label.setText(text, false, false);
}
/** Parse color markup tags and register SKIP tokens. */
private static void parseColorMarkups(TypingLabel label) {
// Get text
final CharSequence text = label.getText();
// Iterate through matches and register skip tokens
Matcher m = PATTERN_MARKUP_STRIP.matcher(text);
while(m.find()) {
final String tag = m.group(0);
final int index = m.start(0);
label.tokenEntries.add(new TokenEntry("SKIP", TokenCategory.SKIP, index, 0, tag));
}
}
/** Returns a float value parsed from the given String, or the default value if the string couldn't be parsed. */
static float stringToFloat(String str, float defaultValue) {
if(str != null) {
try {
return Float.parseFloat(str);
} catch(Exception e) {
}
}
return defaultValue;
}
/** Returns a boolean value parsed from the given String, or the default value if the string couldn't be parsed. */
static boolean stringToBoolean(String str) {
if(str != null) {
for(String booleanTrue : BOOLEAN_TRUE) {
if(booleanTrue.equalsIgnoreCase(str)) {
return true;
}
}
}
return false;
}
/** Parses a color from the given string. Returns null if the color couldn't be parsed. */
static Color stringToColor(String str) {
if(str != null) {
// Try to parse named color
Color namedColor = Colors.get(str.toUpperCase());
if(namedColor != null) {
return new Color(namedColor);
}
// Try to parse hex
if(str.length() >= 6) {
try {
return Color.valueOf(str);
} catch(NumberFormatException ignored) {
}
}
}
return null;
}
/** Encloses the given string in brackets to work as a regular color markup tag. */
private static String stringToColorMarkup(String str) {
if(str != null) {
// Upper case
str = str.toUpperCase();
// If color isn't registered by name, try to parse it as an hex code.
Color namedColor = Colors.get(str);
if(namedColor == null) {
boolean isHexWithoutHashChar = str.length() >= 6 && PATTERN_COLOR_HEX_NO_HASH.matches(str);
if(isHexWithoutHashChar) {
str = "#" + str;
}
}
}
// Return color code
return "[" + str + "]";
}
/**
* Returns a compiled {@link Pattern} that groups the token name in the first group and the params in an optional second one. Case
* insensitive.
*/
private static Pattern compileTokenPattern() {
StringBuilder sb = new StringBuilder();
sb.append("\\").append(CURRENT_DELIMITER.open).append("(");
Array tokens = new Array<>();
TypingConfig.EFFECT_START_TOKENS.keys().toArray(tokens);
TypingConfig.EFFECT_END_TOKENS.keys().toArray(tokens);
for(InternalToken token : InternalToken.values()) {
tokens.add(token.name);
}
for(int i = 0; i < tokens.size; i++) {
sb.append(tokens.get(i));
if((i + 1) < tokens.size) sb.append('|');
}
sb.append(")(?:=([;:?=^_ #-'*-.\\.\\w]+))?\\").append(CURRENT_DELIMITER.close);
return Pattern.compile(sb.toString(), REFlags.IGNORE_CASE);
}
/** Returns the replacement string intended to be used on {RESET} tokens. */
private static String getResetReplacement() {
Array tokens = new Array<>();
TypingConfig.EFFECT_END_TOKENS.keys().toArray(tokens);
tokens.add("CLEARCOLOR");
tokens.add("NORMAL");
StringBuilder sb = new StringBuilder();
for(String token : tokens) {
sb.append(CURRENT_DELIMITER.open).append(token).append(CURRENT_DELIMITER.close);
}
return sb.toString();
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TokenCategory.java
================================================
package com.rafaskoberg.gdx.typinglabel;
public enum TokenCategory {
WAIT,
SPEED,
COLOR,
VARIABLE,
IF,
EVENT,
RESET,
SKIP,
EFFECT_START,
EFFECT_END
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TokenDelimiter.java
================================================
package com.rafaskoberg.gdx.typinglabel;
/**
* Enum that lists all supported delimiters for tokens.
*/
public enum TokenDelimiter {
/** {TOKEN} */
CURLY_BRACKETS('{', '}'),
/** [TOKEN] */
BRACKETS('[', ']'),
/** (TOKEN) */
PARENTHESES('(', ')');
public final char open;
public final char close;
TokenDelimiter(char open, char close) {
this.open = open;
this.close = close;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TokenEntry.java
================================================
package com.rafaskoberg.gdx.typinglabel;
/** Container representing a token, parsed parameters and its position in text. */
class TokenEntry implements Comparable {
String token;
TokenCategory category;
int index;
float floatValue;
String stringValue;
Effect effect;
TokenEntry(String token, TokenCategory category, int index, float floatValue, String stringValue) {
this.token = token;
this.category = category;
this.index = index;
this.floatValue = floatValue;
this.stringValue = stringValue;
}
@Override
public int compareTo(TokenEntry o) {
return Integer.compare(index, o.index);
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingAdapter.java
================================================
package com.rafaskoberg.gdx.typinglabel;
/** Simple listener for label events. You can derive from this and only override what you are interested in. */
public class TypingAdapter implements TypingListener {
@Override
public void event(String event) {
}
@Override
public void end() {
}
@Override
public String replaceVariable(String variable) {
return null;
}
@Override
public void onChar(Character ch) {
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingConfig.java
================================================
package com.rafaskoberg.gdx.typinglabel;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.utils.ObjectFloatMap;
import com.badlogic.gdx.utils.ObjectMap;
import com.rafaskoberg.gdx.typinglabel.effects.BlinkEffect;
import com.rafaskoberg.gdx.typinglabel.effects.EaseEffect;
import com.rafaskoberg.gdx.typinglabel.effects.FadeEffect;
import com.rafaskoberg.gdx.typinglabel.effects.GradientEffect;
import com.rafaskoberg.gdx.typinglabel.effects.HangEffect;
import com.rafaskoberg.gdx.typinglabel.effects.JumpEffect;
import com.rafaskoberg.gdx.typinglabel.effects.RainbowEffect;
import com.rafaskoberg.gdx.typinglabel.effects.ShakeEffect;
import com.rafaskoberg.gdx.typinglabel.effects.SickEffect;
import com.rafaskoberg.gdx.typinglabel.effects.SlideEffect;
import com.rafaskoberg.gdx.typinglabel.effects.WaveEffect;
import com.rafaskoberg.gdx.typinglabel.effects.WindEffect;
/** Configuration class that easily allows the user to fine tune the library's functionality. */
public class TypingConfig {
/**
* Whether or not LibGDX's Color Markup
* Language should be enabled when parsing a {@link TypingLabel}. Note that this library doesn't truly handle
* colors, but simply convert them to the markup format. If markup is disabled, color tokens will be ignored.
*/
public static boolean FORCE_COLOR_MARKUP_BY_DEFAULT = true;
/** Default time in seconds that an empty {@code WAIT} token should wait for. Default value is {@code 0.250}. */
public static float DEFAULT_WAIT_VALUE = 0.250f;
/** Time in seconds that takes for each char to appear in the default speed. Default value is {@code 0.035}. */
public static float DEFAULT_SPEED_PER_CHAR = 0.035f;
/**
* Minimum value for the {@code SPEED} token. This value divides {@link #DEFAULT_SPEED_PER_CHAR} to calculate the
* final speed. Keep it above zero. Default value is {@code 0.001}.
*/
public static float MIN_SPEED_MODIFIER = 0.001f;
/**
* Maximum value for the {@code SPEED} token. This value divides {@link #DEFAULT_SPEED_PER_CHAR} to calculate the
* final speed. Default value is {@code 100}.
*/
public static float MAX_SPEED_MODIFIER = 100.0f;
/**
* Defines how many chars can appear per frame. Use a value less than {@code 1} to disable this limit. Default value
* is {@code -1}.
*/
public static int CHAR_LIMIT_PER_FRAME = -1;
/** Default color for the {@code CLEARCOLOR} token. Can be overriden by {@link TypingLabel#getClearColor()}. */
public static Color DEFAULT_CLEAR_COLOR = new Color(Color.WHITE);
/** Characters used to start and end tokens. Defaults to {@link TokenDelimiter#CURLY_BRACKETS}.*/
public static TokenDelimiter TOKEN_DELIMITER = TokenDelimiter.CURLY_BRACKETS;
/**
* Returns a map of characters and their respective interval multipliers, of which the interval to the next char
* should be multiplied for.
*/
public static ObjectFloatMap INTERVAL_MULTIPLIERS_BY_CHAR = new ObjectFloatMap();
/** Map of global variables that affect all {@link TypingLabel} instances at once. */
public static final ObjectMap GLOBAL_VARS = new ObjectMap<>();
/** Map of start tokens and their effect classes. Internal use only. */
static final ObjectMap> EFFECT_START_TOKENS = new ObjectMap<>();
/** Map of end tokens and their effect classes. Internal use only. */
static final ObjectMap> EFFECT_END_TOKENS = new ObjectMap<>();
/** Whether or not effect tokens are dirty and need to be recalculated. */
static boolean dirtyEffectMaps = true;
/**
* Registers a new effect to TypingLabel.
*
* @param startTokenName Name of the token that starts the effect, such as WAVE.
* @param endTokenName Name of the token that ends the effect, such as ENDWAVE.
* @param effectClass Class of the effect, such as WaveEffect.class.
*/
public static void registerEffect(String startTokenName, String endTokenName, Class extends Effect> effectClass) {
EFFECT_START_TOKENS.put(startTokenName.toUpperCase(), effectClass);
EFFECT_END_TOKENS.put(endTokenName.toUpperCase(), effectClass);
dirtyEffectMaps = true;
}
/**
* Unregisters an effect from TypingLabel.
*
* @param startTokenName Name of the token that starts the effect, such as WAVE.
* @param endTokenName Name of the token that ends the effect, such as ENDWAVE.
*/
public static void unregisterEffect(String startTokenName, String endTokenName) {
EFFECT_START_TOKENS.remove(startTokenName.toUpperCase());
EFFECT_END_TOKENS.remove(endTokenName.toUpperCase());
}
static {
// Generate default char intervals
INTERVAL_MULTIPLIERS_BY_CHAR.put(' ', 0.0f);
INTERVAL_MULTIPLIERS_BY_CHAR.put(':', 1.5f);
INTERVAL_MULTIPLIERS_BY_CHAR.put(',', 2.5f);
INTERVAL_MULTIPLIERS_BY_CHAR.put('.', 2.5f);
INTERVAL_MULTIPLIERS_BY_CHAR.put('!', 5.0f);
INTERVAL_MULTIPLIERS_BY_CHAR.put('?', 5.0f);
INTERVAL_MULTIPLIERS_BY_CHAR.put('\n', 20f);
// Register default tokens
registerEffect("EASE", "ENDEASE", EaseEffect.class);
registerEffect("HANG", "ENDHANG", HangEffect.class);
registerEffect("JUMP", "ENDJUMP", JumpEffect.class);
registerEffect("SHAKE", "ENDSHAKE", ShakeEffect.class);
registerEffect("SICK", "ENDSICK", SickEffect.class);
registerEffect("SLIDE", "ENDSLIDE", SlideEffect.class);
registerEffect("WAVE", "ENDWAVE", WaveEffect.class);
registerEffect("WIND", "ENDWIND", WindEffect.class);
registerEffect("RAINBOW", "ENDRAINBOW", RainbowEffect.class);
registerEffect("GRADIENT", "ENDGRADIENT", GradientEffect.class);
registerEffect("FADE", "ENDFADE", FadeEffect.class);
registerEffect("BLINK", "ENDBLINK", BlinkEffect.class);
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingGlyph.java
================================================
package com.rafaskoberg.gdx.typinglabel;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.GlyphLayout.GlyphRun;
/** Extension of {@link Glyph} with additional data exposed to the user. */
public class TypingGlyph extends Glyph {
/** The color of the run this glyph belongs to, as an ABGR8888 int. */
public int runColor = 0xFFFFFFFF;
/** Internal index associated with this glyph. Internal use only. Defaults to -1. */
int internalIndex = -1;
/** Color of this glyph. If set to null, the run's color will be used. Defaults to null. */
public Color color = null;
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingLabel.java
================================================
package com.rafaskoberg.gdx.typinglabel;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.graphics.g2d.BitmapFontCache;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.GlyphLayout.GlyphRun;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.*;
import com.badlogic.gdx.utils.StringBuilder;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import com.badlogic.gdx.utils.reflect.ClassReflection;
/**
* An extension of {@link Label} that progressively shows the text as if it was being typed in real time, and allows the
* use of tokens in the following format: {TOKEN=PARAMETER}.
*/
public class TypingLabel extends Label {
///////////////////////
/// --- Members --- ///
///////////////////////
// Collections
private final ObjectMap variables = new ObjectMap();
protected final Array tokenEntries = new Array();
// Config
private Color clearColor = new Color(TypingConfig.DEFAULT_CLEAR_COLOR);
private final Array listeners = new Array<>(TypingListener.class);
boolean forceMarkupColor = TypingConfig.FORCE_COLOR_MARKUP_BY_DEFAULT;
// Internal state
private final StringBuilder originalText = new StringBuilder();
private final Array glyphCache = new Array();
private final IntArray glyphRunCapacities = new IntArray();
private final IntArray offsetCache = new IntArray();
private final IntArray layoutLineBreaks = new IntArray();
private final Array activeEffects = new Array();
private float textSpeed = TypingConfig.DEFAULT_SPEED_PER_CHAR;
private float charCooldown = textSpeed;
private int rawCharIndex = -2; // All chars, including color codes
private int glyphCharIndex = -1; // Only renderable chars, excludes color codes
private int glyphCharCompensation = 0;
private int cachedGlyphCharIndex = -1; // Last glyphCharIndex sent to the cache
private float lastLayoutX = 0;
private float lastLayoutY = 0;
private boolean parsed = false;
private boolean paused = false;
private boolean ended = false;
private boolean skipping = false;
private boolean ignoringEvents = false;
private boolean ignoringEffects = false;
private String defaultToken = "";
// Superclass mirroring
boolean wrap;
String ellipsis;
float lastPrefHeight;
boolean fontScaleChanged = false;
private static final Color tempColor = new Color();
////////////////////////////
/// --- Constructors --- ///
////////////////////////////
public TypingLabel(CharSequence text, LabelStyle style) {
super(text, style);
saveOriginalText();
}
public TypingLabel(CharSequence text, Skin skin, String fontName, Color color) {
super(text, skin, fontName, color);
saveOriginalText();
}
public TypingLabel(CharSequence text, Skin skin, String fontName, String colorName) {
super(text, skin, fontName, colorName);
saveOriginalText();
}
public TypingLabel(CharSequence text, Skin skin, String styleName) {
super(text, skin, styleName);
saveOriginalText();
}
public TypingLabel(CharSequence text, Skin skin) {
super(text, skin);
saveOriginalText();
}
/////////////////////////////
/// --- Text Handling --- ///
/////////////////////////////
/**
* Modifies the text of this label. If the char progression is already running, it's highly recommended to use
* {@link #restart(CharSequence)} instead.
*/
@Override
public void setText(CharSequence newText) {
this.setText(newText, true);
}
/**
* Sets the text of this label.
*
* @param modifyOriginalText Flag determining if the original text should be modified as well. If {@code false},
* only the display text is changed while the original text is untouched.
* @see #restart(CharSequence)
*/
protected void setText(CharSequence newText, boolean modifyOriginalText) {
setText(newText, modifyOriginalText, true);
}
/**
* Sets the text of this label.
*
* @param modifyOriginalText Flag determining if the original text should be modified as well. If {@code false},
* only the display text is changed while the original text is untouched.
* @param restart Whether or not this label should restart. Defaults to true.
* @see #restart(CharSequence)
*/
protected void setText(CharSequence newText, boolean modifyOriginalText, boolean restart) {
final boolean hasEnded = this.hasEnded();
super.setText(newText);
if(modifyOriginalText) saveOriginalText();
if(restart) {
this.restart();
}
if(hasEnded) {
this.skipToTheEnd(true, false);
}
}
/** Similar to {@link #getText()}, but returns the original text with all the tokens unchanged. */
public StringBuilder getOriginalText() {
return originalText;
}
/**
* Copies the content of {@link #getText()} to the {@link StringBuilder} containing the original text with all
* tokens unchanged.
*/
protected void saveOriginalText() {
originalText.setLength(0);
originalText.insert(0, this.getText());
originalText.trimToSize();
}
/**
* Restores the original text with all tokens unchanged to this label. Make sure to call {@link #parseTokens()} to
* parse the tokens again.
*/
protected void restoreOriginalText() {
super.setText(originalText);
this.parsed = false;
}
////////////////////////////
/// --- External API --- ///
////////////////////////////
/** Returns the {@link TypingListener}s associated with this label. May be empty. */
public Array getTypingListeners() {
return listeners;
}
/** Adds a {@link TypingListener} to this label. */
public void addTypingListener(TypingListener listener) {
listeners.add(listener);
}
/** Clears all {@link TypingListener}s associated with this label. */
public void clearTypingListeners() {
listeners.clear();
}
/**
* Returns a {@link Color} instance with the color to be used on {@code CLEARCOLOR} tokens. Modify this instance to
* change the token color. Default value is specified by {@link TypingConfig}.
*
* @see TypingConfig#DEFAULT_CLEAR_COLOR
*/
public Color getClearColor() {
return clearColor;
}
/**
* Sets whether or not this instance should enable markup color by force.
*
* @see TypingConfig#FORCE_COLOR_MARKUP_BY_DEFAULT
*/
public void setForceMarkupColor(boolean forceMarkupColor) {
this.forceMarkupColor = forceMarkupColor;
}
/** Returns the default token being used in this label. Defaults to empty string. */
public String getDefaultToken() {
return defaultToken;
}
/**
* Sets the default token being used in this label. This token will be used before the label's text, and after each
* {RESET} call. Useful if you want a certain token to be active at all times without having to type it all the
* time.
*/
public void setDefaultToken(String defaultToken) {
this.defaultToken = defaultToken == null ? "" : defaultToken;
this.parsed = false;
}
/** Parses all tokens of this label. Use this after setting the text and any variables that should be replaced. */
public void parseTokens() {
this.setText(getDefaultToken() + getText(), false, false);
Parser.parseTokens(this);
parsed = true;
}
/**
* Skips the char progression to the end, showing the entire label. Useful for when users don't want to wait for too
* long. Ignores all subsequent events by default.
*/
public void skipToTheEnd() {
skipToTheEnd(true);
}
/**
* Skips the char progression to the end, showing the entire label. Useful for when users don't want to wait for too
* long.
*
* @param ignoreEvents If {@code true}, skipped events won't be reported to the listener.
*/
public void skipToTheEnd(boolean ignoreEvents) {
skipToTheEnd(ignoreEvents, false);
}
/**
* Skips the char progression to the end, showing the entire label. Useful for when users don't want to wait for too
* long.
*
* @param ignoreEvents If {@code true}, skipped events won't be reported to the listener.
* @param ignoreEffects If {@code true}, all text effects will be instantly cancelled.
*/
public void skipToTheEnd(boolean ignoreEvents, boolean ignoreEffects) {
skipping = true;
ignoringEvents = ignoreEvents;
ignoringEffects = ignoreEffects;
}
/**
* Cancels calls to {@link #skipToTheEnd()}. Useful if you need to restore the label's normal behavior at some event
* after skipping.
*/
public void cancelSkipping() {
if(skipping) {
skipping = false;
ignoringEvents = false;
ignoringEffects = false;
}
}
/**
* Returns whether or not this label is currently skipping its typing progression all the way to the end. This is
* only true if skipToTheEnd is called.
*/
public boolean isSkipping() {
return skipping;
}
/** Returns whether or not this label is paused. */
public boolean isPaused() {
return paused;
}
/** Pauses this label's character progression. */
public void pause() {
paused = true;
}
/** Resumes this label's character progression. */
public void resume() {
paused = false;
}
/** Returns whether or not this label's char progression has ended. */
public boolean hasEnded() {
return ended;
}
/**
* Restarts this label with the original text and starts the char progression right away. All tokens are
* automatically parsed.
*/
public void restart() {
restart(getOriginalText());
}
/**
* Restarts this label with the given text and starts the char progression right away. All tokens are automatically
* parsed.
*/
public void restart(CharSequence newText) {
// Reset cache collections
GlyphUtils.freeAll(glyphCache);
glyphCache.clear();
glyphRunCapacities.clear();
offsetCache.clear();
layoutLineBreaks.clear();
activeEffects.clear();
// Reset state
textSpeed = TypingConfig.DEFAULT_SPEED_PER_CHAR;
charCooldown = textSpeed;
rawCharIndex = -2;
glyphCharIndex = -1;
glyphCharCompensation = 0;
cachedGlyphCharIndex = -1;
lastLayoutX = 0;
lastLayoutY = 0;
parsed = false;
paused = false;
ended = false;
skipping = false;
ignoringEvents = false;
ignoringEffects = false;
// Set new text
this.setText(newText, true, false);
invalidate();
// Parse tokens
tokenEntries.clear();
parseTokens();
}
/** Returns an {@link ObjectMap} with all the variable names and their respective replacement values. */
public ObjectMap getVariables() {
return variables;
}
/** Registers a variable and its respective replacement value to this label. */
public void setVariable(String var, String value) {
variables.put(var.toUpperCase(), value);
}
/** Registers a set of variables and their respective replacement values to this label. */
public void setVariables(ObjectMap variableMap) {
this.variables.clear();
for(Entry entry : variableMap.entries()) {
this.variables.put(entry.key.toUpperCase(), entry.value);
}
}
/** Registers a set of variables and their respective replacement values to this label. */
public void setVariables(java.util.Map variableMap) {
this.variables.clear();
for(java.util.Map.Entry entry : variableMap.entrySet()) {
this.variables.put(entry.getKey().toUpperCase(), entry.getValue());
}
}
/** Removes all variables from this label. */
public void clearVariables() {
this.variables.clear();
}
//////////////////////////////////
/// --- Core Functionality --- ///
//////////////////////////////////
@Override
public void act(float delta) {
super.act(delta);
// Force token parsing
if(!parsed) {
parseTokens();
}
// Update cooldown and process char progression
if(skipping || (!ended && !paused)) {
if(skipping || (charCooldown -= delta) < 0.0f) {
processCharProgression();
}
}
// Restore glyph offsets
if(activeEffects.size > 0) {
for(int i = 0; i < glyphCache.size; i++) {
TypingGlyph glyph = glyphCache.get(i);
glyph.xoffset = offsetCache.get(i * 2);
glyph.yoffset = offsetCache.get(i * 2 + 1);
}
}
// Apply effects
if(!ignoringEffects) {
for(int i = activeEffects.size - 1; i >= 0; i--) {
Effect effect = activeEffects.get(i);
effect.update(delta);
int start = effect.indexStart;
int end = effect.indexEnd >= 0 ? effect.indexEnd : glyphCharIndex;
// If effect is finished, remove it
if(effect.isFinished()) {
activeEffects.removeIndex(i);
continue;
}
// Apply effect to glyph
for(int j = Math.max(0, start); j <= glyphCharIndex && j <= end && j < glyphCache.size; j++) {
TypingGlyph glyph = glyphCache.get(j);
effect.apply(glyph, j, delta);
}
}
}
}
/** Proccess char progression according to current cooldown and process all tokens in the current index. */
private void processCharProgression() {
// Keep a counter of how many chars we're processing in this tick.
int charCounter = 0;
// Process chars while there's room for it
while(skipping || charCooldown < 0.0f) {
// Apply compensation to glyph index, if any
if(glyphCharCompensation != 0) {
if(glyphCharCompensation > 0) {
glyphCharIndex++;
glyphCharCompensation--;
} else {
glyphCharIndex--;
glyphCharCompensation++;
}
// Increment cooldown and wait for it
charCooldown += textSpeed;
continue;
}
// Increase raw char index
rawCharIndex++;
// Get next character and calculate cooldown increment
int safeIndex = MathUtils.clamp(rawCharIndex, 0, getText().length - 1);
char primitiveChar = '\u0000'; // Null character by default
if(getText().length > 0) {
primitiveChar = getText().charAt(safeIndex);
float intervalMultiplier = TypingConfig.INTERVAL_MULTIPLIERS_BY_CHAR.get(primitiveChar, 1);
charCooldown += textSpeed * intervalMultiplier;
}
// If char progression is finished, or if text is empty, notify listener and abort routine
int textLen = getText().length;
if(textLen == 0 || rawCharIndex >= textLen) {
if(!ended) {
ended = true;
skipping = false;
for(TypingListener listener : listeners) {
listener.end();
}
}
return;
}
// Detect layout line breaks
boolean isLayoutLineBreak = false;
if(layoutLineBreaks.contains(glyphCharIndex)) {
layoutLineBreaks.removeValue(glyphCharIndex);
isLayoutLineBreak = true;
}
// Increase glyph char index for all characters, except new lines.
if(rawCharIndex >= 0 && primitiveChar != '\n' && primitiveChar != '\r' && !isLayoutLineBreak) glyphCharIndex++;
// Process tokens according to the current index
while(tokenEntries.size > 0 && tokenEntries.peek().index == rawCharIndex) {
TokenEntry entry = tokenEntries.pop();
String token = entry.token;
TokenCategory category = entry.category;
// Process tokens
switch(category) {
case SPEED: {
textSpeed = entry.floatValue;
continue;
}
case WAIT: {
glyphCharIndex--;
glyphCharCompensation++;
charCooldown += entry.floatValue;
continue;
}
case SKIP: {
if(entry.stringValue != null) {
rawCharIndex += entry.stringValue.length();
}
continue;
}
case EVENT: {
if(!ignoringEvents) {
for(TypingListener listener : listeners) {
listener.event(entry.stringValue);
}
}
continue;
}
case EFFECT_START:
case EFFECT_END: {
// Get effect class
boolean isStart = category == TokenCategory.EFFECT_START;
Class extends Effect> effectClass = isStart ? TypingConfig.EFFECT_START_TOKENS.get(token) : TypingConfig.EFFECT_END_TOKENS.get(token);
// End all effects of the same type
for(int i = 0; i < activeEffects.size; i++) {
Effect effect = activeEffects.get(i);
if(effect.indexEnd < 0) {
if(ClassReflection.isAssignableFrom(effectClass, effect.getClass())) {
effect.indexEnd = glyphCharIndex - 1;
}
}
}
// Create new effect if necessary
if(isStart) {
entry.effect.indexStart = glyphCharIndex;
activeEffects.add(entry.effect);
}
}
}
}
// Notify listener about char progression
int nextIndex = MathUtils.clamp(rawCharIndex, 0, getText().length - 1);
Character nextChar = nextIndex == 0 ? null : getText().charAt(nextIndex);
if(nextChar != null) {
for(TypingListener listener : listeners) {
listener.onChar(nextChar);
}
}
// Increment char counter
charCounter++;
// Break loop if this was our first glyph to prevent glyph issues.
if(glyphCharIndex == -1) {
charCooldown = textSpeed;
break;
}
// Break loop if enough chars were processed
charCounter++;
int charLimit = TypingConfig.CHAR_LIMIT_PER_FRAME;
if(!skipping && charLimit > 0 && charCounter > charLimit) {
charCooldown = Math.max(charCooldown, textSpeed);
break;
}
}
}
@Override
public boolean remove() {
GlyphUtils.freeAll(glyphCache);
glyphCache.clear();
return super.remove();
}
////////////////////////////////////
/// --- Superclass Mirroring --- ///
////////////////////////////////////
@Override
public BitmapFontCache getBitmapFontCache() {
return super.getBitmapFontCache();
}
@Override
public void setEllipsis(String ellipsis) {
// Mimics superclass but keeps an accessible reference
super.setEllipsis(ellipsis);
this.ellipsis = ellipsis;
}
@Override
public void setEllipsis(boolean ellipsis) {
// Mimics superclass but keeps an accessible reference
super.setEllipsis(ellipsis);
if(ellipsis)
this.ellipsis = "...";
else
this.ellipsis = null;
}
@Override
public void setWrap(boolean wrap) {
// Mimics superclass but keeps an accessible reference
super.setWrap(wrap);
this.wrap = wrap;
}
@Override
public void setFontScale(float fontScale) {
super.setFontScale(fontScale);
this.fontScaleChanged = true;
}
@Override
public void setFontScale(float fontScaleX, float fontScaleY) {
super.setFontScale(fontScaleX, fontScaleY);
this.fontScaleChanged = true;
}
@Override
public void setFontScaleX(float fontScaleX) {
super.setFontScaleX(fontScaleX);
this.fontScaleChanged = true;
}
@Override
public void setFontScaleY(float fontScaleY) {
super.setFontScaleY(fontScaleY);
this.fontScaleChanged = true;
}
@Override
public void layout() {
// --- SUPERCLASS IMPLEMENTATION ---
BitmapFontCache cache = getBitmapFontCache();
StringBuilder text = getText();
GlyphLayout layout = super.getGlyphLayout();
int lineAlign = getLineAlign();
int labelAlign = getLabelAlign();
LabelStyle style = getStyle();
BitmapFont font = cache.getFont();
float oldScaleX = font.getScaleX();
float oldScaleY = font.getScaleY();
if(fontScaleChanged) font.getData().setScale(getFontScaleX(), getFontScaleY());
boolean wrap = this.wrap && ellipsis == null;
if(wrap) {
float prefHeight = getPrefHeight();
if(prefHeight != lastPrefHeight) {
lastPrefHeight = prefHeight;
invalidateHierarchy();
}
}
float width = getWidth(), height = getHeight();
Drawable background = style.background;
float x = 0, y = 0;
if(background != null) {
x = background.getLeftWidth();
y = background.getBottomHeight();
width -= background.getLeftWidth() + background.getRightWidth();
height -= background.getBottomHeight() + background.getTopHeight();
}
float textWidth, textHeight;
if(wrap || text.indexOf("\n") != -1) {
// If the text can span multiple lines, determine the text's actual size so it can be aligned within the label.
layout.setText(font, text, 0, text.length, Color.WHITE, width, lineAlign, wrap, ellipsis);
textWidth = layout.width;
textHeight = layout.height;
if((labelAlign & Align.left) == 0) {
if((labelAlign & Align.right) != 0)
x += width - textWidth;
else
x += (width - textWidth) / 2;
}
} else {
textWidth = width;
textHeight = font.getData().capHeight;
}
if((labelAlign & Align.top) != 0) {
y += cache.getFont().isFlipped() ? 0 : height - textHeight;
y += style.font.getDescent();
} else if((labelAlign & Align.bottom) != 0) {
y += cache.getFont().isFlipped() ? height - textHeight : 0;
y -= style.font.getDescent();
} else {
y += (height - textHeight) / 2;
}
if(!cache.getFont().isFlipped()) y += textHeight;
layout.setText(font, text, 0, text.length, Color.WHITE, textWidth, lineAlign, wrap, ellipsis);
cache.setText(layout, x, y);
if(fontScaleChanged) font.getData().setScale(oldScaleX, oldScaleY);
// --- END OF SUPERCLASS IMPLEMENTATION ---
// Store coordinates passed to BitmapFontCache
lastLayoutX = x;
lastLayoutY = y;
// Perform cache layout operation, where the magic happens
GlyphUtils.freeAll(glyphCache);
glyphCache.clear();
layoutCache();
}
/**
* Reallocate glyph clones according to the updated {@link GlyphLayout}. This should only be called when the text or
* the layout changes.
*/
private void layoutCache() {
BitmapFontCache cache = getBitmapFontCache();
GlyphLayout layout = super.getGlyphLayout();
Array runs = layout.runs;
IntArray colors = layout.colors;
// Reset layout line breaks
layoutLineBreaks.clear();
// Store GlyphRun sizes and count how many glyphs we have
int glyphCount = 0;
glyphRunCapacities.setSize(runs.size);
for(int i = 0; i < runs.size; i++) {
Array glyphs = runs.get(i).glyphs;
glyphRunCapacities.set(i, glyphs.size);
glyphCount += glyphs.size;
}
// Make sure our cache array can hold all glyphs
if(glyphCache.size < glyphCount) {
glyphCache.setSize(glyphCount);
offsetCache.setSize(glyphCount * 2);
}
// Clone original glyphs with independent instances
int index = -1;
float lastY = 0;
int colorIndex = 1;
int currentColor = colors.size < 2 ? 0xFFFFFFFF : colors.get(1);
int colorChange = colors.size < 4 ? glyphCount : colors.get(2);
for(int i = 0; i < runs.size; i++) {
GlyphRun run = runs.get(i);
Array glyphs = run.glyphs;
for(int j = 0; j < glyphs.size; j++) {
// Detect and store layout line breaks
if(!MathUtils.isEqual(run.y, lastY)) {
lastY = run.y;
layoutLineBreaks.add(index);
}
// Increment index
index++;
if(index >= colorChange && colorIndex + 2 < colors.size)
{
currentColor = colors.get(colorIndex += 2);
colorChange = colors.size <= colorIndex + 1 ? glyphCount : colors.get(colorIndex + 1);
}
// Get original glyph
Glyph original = glyphs.get(j);
// Get clone glyph
TypingGlyph clone = null;
if(index < glyphCache.size) {
clone = glyphCache.get(index);
}
if(clone == null) {
clone = GlyphUtils.obtain();
glyphCache.set(index, clone);
}
GlyphUtils.clone(original, clone);
clone.width *= getFontScaleX();
clone.height *= getFontScaleY();
clone.xoffset *= getFontScaleX();
clone.yoffset *= getFontScaleY();
clone.runColor = currentColor;
// Store offset data
offsetCache.set(index * 2, clone.xoffset);
offsetCache.set(index * 2 + 1, clone.yoffset);
// Replace glyph in original array
glyphs.set(j, clone);
}
}
// Remove exceeding glyphs from original array
int glyphCountdown = glyphCharIndex;
for(int i = 0; i < runs.size; i++) {
Array glyphs = runs.get(i).glyphs;
if(glyphs.size < glyphCountdown) {
glyphCountdown -= glyphs.size;
continue;
}
for(int j = 0; j < glyphs.size; j++) {
if(glyphCountdown < 0) {
glyphs.removeRange(j, glyphs.size - 1);
break;
}
glyphCountdown--;
}
}
// Pass new layout with custom glyphs to BitmapFontCache
cache.setText(layout, lastLayoutX, lastLayoutY);
}
/** Adds cached glyphs to the active BitmapFontCache as the char index progresses. */
private void addMissingGlyphs() {
// Add additional glyphs to layout array, if any
int glyphLeft = glyphCharIndex - cachedGlyphCharIndex;
if(glyphLeft < 1) return;
// Get runs
GlyphLayout layout = super.getGlyphLayout();
Array runs = layout.runs;
// Iterate through GlyphRuns to find the next glyph spot
int glyphCount = 0;
for(int runIndex = 0; runIndex < glyphRunCapacities.size; runIndex++) {
int runCapacity = glyphRunCapacities.get(runIndex);
if((glyphCount + runCapacity) < cachedGlyphCharIndex) {
glyphCount += runCapacity;
continue;
}
// Get run and increase glyphCount up to its current size
Array glyphs = runs.get(runIndex).glyphs;
glyphCount += glyphs.size;
// Next glyphs go here
while(glyphLeft > 0) {
// Skip run if this one is full
int runSize = glyphs.size;
if(runCapacity == runSize) {
break;
}
// Put new glyph to this run
cachedGlyphCharIndex++;
TypingGlyph glyph = glyphCache.get(cachedGlyphCharIndex);
glyphs.add(glyph);
// Cache glyph's vertex index
glyph.internalIndex = glyphCount;
// Advance glyph count
glyphCount++;
glyphLeft--;
}
}
}
@Override
public void draw(Batch batch, float parentAlpha) {
super.validate();
addMissingGlyphs();
// Update cache with new glyphs
BitmapFontCache bitmapFontCache = getBitmapFontCache();
getBitmapFontCache().setText(getGlyphLayout(), lastLayoutX, lastLayoutY);
// --- SUPERCLASS IMPLEMENTATION ---
// This section has to be copied from Label, since we can't call super.draw() without messing up our color.
validate();
Color color = tempColor.set(getColor());
color.a *= parentAlpha;
if (getStyle().background != null) {
batch.setColor(color.r, color.g, color.b, color.a);
getStyle().background.draw(batch, getX(), getY(), getWidth(), getHeight());
}
if (getStyle().fontColor != null) color.mul(getStyle().fontColor);
// --- END OF SUPERCLASS IMPLEMENTATION ---
// Here we store color as its components, to avoid producing garbage and to allow modifying the local color.
float r = color.r, g = color.g, b = color.b, a = color.a;
for(TypingGlyph glyph : glyphCache) {
if (glyph.internalIndex >= 0) {
if (glyph.color != null) {
// Unless we want to use a packed float, it's easiest to pass a Color object here, multiplying this
// Label color (as its components) by the color of the individual glyph.
bitmapFontCache.setColors(
Color.toFloatBits(r * glyph.color.r, g * glyph.color.g, b * glyph.color.b, a * glyph.color.a),
glyph.internalIndex, glyph.internalIndex + 1);
} else if(a < 1f) {
bitmapFontCache.setColors(color, glyph.internalIndex, glyph.internalIndex + 1);
}
}
}
// --- SUPERCLASS IMPLEMENTATION ---
// This also replicates Label. Note that we don't call the super-method.
bitmapFontCache.setPosition(getX(), getY());
bitmapFontCache.draw(batch);
// --- END OF SUPERCLASS IMPLEMENTATION ---
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/TypingListener.java
================================================
package com.rafaskoberg.gdx.typinglabel;
/** Simple listener for label events. */
public interface TypingListener {
/**
* Called each time an {@code EVENT} token is processed.
*
* @param event Name of the event specified in the token. e.g. {EVENT=player_name} will have
* player_name as argument.
*/
public void event(String event);
/** Called when the char progression reaches the end. */
public void end();
/**
* Called when variable tokens are replaced in text. This is an alternative method to deal with variables, other
* than directly assigning replacement values to the label. Replacements returned by this method have priority over
* direct values, unless {@code null} is returned.
*
* @param variable The variable name assigned to the {VAR} token. For example, in {VAR=townName},
* the variable will be townName
* @return The replacement String, or {@code null} if this method should be ignored and the regular values should be
* used instead.
* @see TypingLabel#setVariable(String, String)
* @see TypingLabel#setVariables(java.util.Map)
* @see TypingLabel#setVariables(com.badlogic.gdx.utils.ObjectMap)
*/
public String replaceVariable(String variable);
/**
* Called when a new character is displayed. May be called many times per frame depending on the label
* configurations and text speed. Useful to do a certain action each time a character is displayed, like playing a
* sound effect.
*/
public void onChar(Character ch);
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/BlinkEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.MathUtils;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Blinks the entire text in two different colors at once, without interpolation. */
public class BlinkEffect extends Effect {
private static final float DEFAULT_FREQUENCY = 1f;
private Color color1 = null; // First color of the effect.
private Color color2 = null; // Second color of the effect.
private float frequency = 1; // How frequently the color pattern should move through the text.
private float threshold = 0.5f; // Point to switch colors.
public BlinkEffect(TypingLabel label, String[] params) {
super(label);
// Color 1
if(params.length > 0) {
this.color1 = paramAsColor(params[0]);
}
// Color 2
if(params.length > 1) {
this.color2 = paramAsColor(params[1]);
}
// Frequency
if(params.length > 2) {
this.frequency = paramAsFloat(params[2], 1);
}
// Threshold
if(params.length > 3) {
this.threshold = paramAsFloat(params[3], 0.5f);
}
// Validate parameters
if(this.color1 == null) this.color1 = new Color(Color.WHITE);
if(this.color2 == null) this.color2 = new Color(Color.WHITE);
this.threshold = MathUtils.clamp(this.threshold, 0, 1);
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate progress
float frequencyMod = (1f / frequency) * DEFAULT_FREQUENCY;
float progress = calculateProgress(frequencyMod);
// Calculate color
if(glyph.color == null) glyph.color = new Color(Color.WHITE);
glyph.color.set(progress <= threshold ? color1 : color2);
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/EaseEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.IntFloatMap;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Moves the text vertically easing it into the final position. Doesn't repeat itself. */
public class EaseEffect extends Effect {
private static final float DEFAULT_DISTANCE = 0.15f;
private static final float DEFAULT_INTENSITY = 0.075f;
private float distance = 1; // How much of their height they should move
private float intensity = 1; // How fast the glyphs should move
private boolean elastic = false; // Whether or not the glyphs have an elastic movement
private IntFloatMap timePassedByGlyphIndex = new IntFloatMap();
public EaseEffect(TypingLabel label, String[] params) {
super(label);
// Distance
if(params.length > 0) {
this.distance = paramAsFloat(params[0], 1);
}
//Intensity
if(params.length > 1) {
this.intensity = paramAsFloat(params[1], 1);
}
// Elastic
if(params.length > 2) {
this.elastic = paramAsBoolean(params[2]);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate real intensity
float realIntensity = intensity * (elastic ? 3f : 1f) * DEFAULT_INTENSITY;
// Calculate progress
float timePassed = timePassedByGlyphIndex.getAndIncrement(localIndex, 0, delta);
float progress = MathUtils.clamp(timePassed / realIntensity, 0, 1);
// Calculate offset
Interpolation interpolation = elastic ? Interpolation.swingOut : Interpolation.sine;
float interpolatedValue = interpolation.apply(1, 0, progress);
float y = getLineHeight() * distance * interpolatedValue * DEFAULT_DISTANCE;
// Apply changes
glyph.yoffset += y;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/FadeEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.IntFloatMap;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Fades the text's color from between colors or alphas. Doesn't repeat itself. */
public class FadeEffect extends Effect {
private Color color1 = null; // First color of the effect.
private Color color2 = null; // Second color of the effect.
private float alpha1 = 0; // First alpha of the effect, in case a color isn't provided.
private float alpha2 = 1; // Second alpha of the effect, in case a color isn't provided.
private float fadeDuration = 1; // Duration of the fade effect
private IntFloatMap timePassedByGlyphIndex = new IntFloatMap();
public FadeEffect(TypingLabel label, String[] params) {
super(label);
// Color 1 or Alpha 1
if(params.length > 0) {
this.color1 = paramAsColor(params[0]);
if(this.color1 == null) {
alpha1 = paramAsFloat(params[0], 0);
}
}
// Color 2 or Alpha 2
if(params.length > 1) {
this.color2 = paramAsColor(params[1]);
if(this.color2 == null) {
alpha2 = paramAsFloat(params[1], 1);
}
}
// Fade duration
if(params.length > 2) {
this.fadeDuration = paramAsFloat(params[2], 1);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate progress
float timePassed = timePassedByGlyphIndex.getAndIncrement(localIndex, 0, delta);
float progress = MathUtils.clamp(timePassed / fadeDuration, 0, 1);
// Create glyph color if necessary
if(glyph.color == null) {
glyph.color = new Color(Integer.reverseBytes(glyph.runColor));
}
// Calculate initial color
if(this.color1 == null) {
glyph.color.a = MathUtils.lerp(glyph.color.a, this.alpha1, 1f - progress);
} else {
glyph.color.lerp(this.color1, 1f - progress);
}
// Calculate final color
if(this.color2 == null) {
glyph.color.a = MathUtils.lerp(glyph.color.a, this.alpha2, progress);
} else {
glyph.color.lerp(this.color2, progress);
}
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/GradientEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.graphics.Color;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Tints the text in a gradient pattern. */
public class GradientEffect extends Effect {
private static final float DEFAULT_DISTANCE = 0.975f;
private static final float DEFAULT_FREQUENCY = 2f;
private Color color1 = null; // First color of the gradient.
private Color color2 = null; // Second color of the gradient.
private float distance = 1; // How extensive the rainbow effect should be.
private float frequency = 1; // How frequently the color pattern should move through the text.
public GradientEffect(TypingLabel label, String[] params) {
super(label);
// Color 1
if(params.length > 0) {
this.color1 = paramAsColor(params[0]);
}
// Color 2
if(params.length > 1) {
this.color2 = paramAsColor(params[1]);
}
// Distance
if(params.length > 2) {
this.distance = paramAsFloat(params[2], 1);
}
// Frequency
if(params.length > 3) {
this.frequency = paramAsFloat(params[3], 1);
}
// Validate parameters
if(this.color1 == null) this.color1 = new Color(Color.WHITE);
if(this.color2 == null) this.color2 = new Color(Color.WHITE);
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate progress
float distanceMod = (1f / distance) * (1f - DEFAULT_DISTANCE);
float frequencyMod = (1f / frequency) * DEFAULT_FREQUENCY;
float progress = calculateProgress(frequencyMod, distanceMod * localIndex, true);
// Calculate color
if(glyph.color == null) glyph.color = new Color(Color.WHITE);
glyph.color.set(color1).lerp(color2, progress);
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/HangEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.IntFloatMap;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Hangs the text in midair and suddenly drops it. Doesn't repeat itself. */
public class HangEffect extends Effect {
private static final float DEFAULT_DISTANCE = 0.7f;
private static final float DEFAULT_INTENSITY = 1.5f;
private float distance = 1; // How much of their height they should move
private float intensity = 1; // How fast the glyphs should move
private IntFloatMap timePassedByGlyphIndex = new IntFloatMap();
public HangEffect(TypingLabel label, String[] params) {
super(label);
// Distance
if(params.length > 0) {
this.distance = paramAsFloat(params[0], 1);
}
// Intensity
if(params.length > 1) {
this.intensity = paramAsFloat(params[1], 1);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate real intensity
float realIntensity = intensity * 1f * DEFAULT_INTENSITY;
// Calculate progress
float timePassed = timePassedByGlyphIndex.getAndIncrement(localIndex, 0, delta);
float progress = MathUtils.clamp(timePassed / realIntensity, 0, 1);
// Calculate offset
float interpolation;
float split = 0.7f;
if(progress < split) {
interpolation = Interpolation.pow3Out.apply(0, 1, progress / split);
} else {
interpolation = Interpolation.swing.apply(1, 0, (progress - split) / (1f - split));
}
float distanceFactor = Interpolation.linear.apply(1.0f, 1.5f, progress);
float y = getLineHeight() * distance * distanceFactor * interpolation * DEFAULT_DISTANCE;
// Calculate fadeout
float fadeout = calculateFadeout();
y *= fadeout;
// Apply changes
glyph.yoffset += y;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/JumpEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.math.Interpolation;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Makes the text jumps and falls as if there was gravity. */
public class JumpEffect extends Effect {
private static final float DEFAULT_FREQUENCY = 50f;
private static final float DEFAULT_DISTANCE = 1.33f;
private static final float DEFAULT_INTENSITY = 1f;
private float distance = 1; // How much of their height they should move
private float frequency = 1; // How frequently the wave pattern repeats
private float intensity = 1; // How fast the glyphs should move
public JumpEffect(TypingLabel label, String[] params) {
super(label);
// Distance
if(params.length > 0) {
this.distance = paramAsFloat(params[0], 1);
}
// Frequency
if(params.length > 1) {
this.frequency = paramAsFloat(params[1], 1);
}
// Intensity
if(params.length > 2) {
this.intensity = paramAsFloat(params[2], 1);
}
// Duration
if(params.length > 3) {
this.duration = paramAsFloat(params[3], -1);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate progress
float progressModifier = (1f / intensity) * DEFAULT_INTENSITY;
float normalFrequency = (1f / frequency) * DEFAULT_FREQUENCY;
float progressOffset = localIndex / normalFrequency;
float progress = calculateProgress(progressModifier, -progressOffset, false);
// Calculate offset
float interpolation = 0;
float split = 0.2f;
if(progress < split) {
interpolation = Interpolation.pow2Out.apply(0, 1, progress / split);
} else {
interpolation = Interpolation.bounceOut.apply(1, 0, (progress - split) / (1f - split));
}
float y = getLineHeight() * distance * interpolation * DEFAULT_DISTANCE;
// Calculate fadeout
float fadeout = calculateFadeout();
y *= fadeout;
// Apply changes
glyph.yoffset += y;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/RainbowEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.graphics.Color;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
import com.rafaskoberg.gdx.typinglabel.utils.ColorUtils;
/** Tints the text in a rainbow pattern. */
public class RainbowEffect extends Effect {
private static final float DEFAULT_DISTANCE = 0.975f;
private static final float DEFAULT_FREQUENCY = 2f;
private float distance = 1; // How extensive the rainbow effect should be.
private float frequency = 1; // How frequently the color pattern should move through the text.
private float saturation = 1; // Color saturation
private float brightness = 1; // Color brightness
public RainbowEffect(TypingLabel label, String[] params) {
super(label);
// Distance
if(params.length > 0) {
this.distance = paramAsFloat(params[0], 1);
}
// Frequency
if(params.length > 1) {
this.frequency = paramAsFloat(params[1], 1);
}
// Saturation
if(params.length > 2) {
this.saturation = paramAsFloat(params[2], 1);
}
// Brightness
if(params.length > 3) {
this.brightness = paramAsFloat(params[3], 1);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate progress
float distanceMod = (1f / distance) * (1f - DEFAULT_DISTANCE);
float frequencyMod = (1f / frequency) * DEFAULT_FREQUENCY;
float progress = calculateProgress(frequencyMod, distanceMod * localIndex, false);
// Calculate color
if(glyph.color == null) {
glyph.color = new Color(Color.WHITE);
}
ColorUtils.HSVtoRGB(360f * progress, saturation * 100f, brightness * 100f, glyph.color);
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/ShakeEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.FloatArray;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Shakes the text in a random pattern. */
public class ShakeEffect extends Effect {
private static final float DEFAULT_DISTANCE = 0.12f;
private static final float DEFAULT_INTENSITY = 0.5f;
private final FloatArray lastOffsets = new FloatArray();
private float distance = 1; // How far the glyphs should move
private float intensity = 1; // How fast the glyphs should move
public ShakeEffect(TypingLabel label, String[] params) {
super(label);
// Distance
if(params.length > 0) {
this.distance = paramAsFloat(params[0], 1);
}
// Intensity
if(params.length > 1) {
this.intensity = paramAsFloat(params[1], 1);
}
// Duration
if(params.length > 2) {
this.duration = paramAsFloat(params[2], -1);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Make sure we can hold enough entries for the current index
if(localIndex >= lastOffsets.size / 2) {
lastOffsets.setSize(lastOffsets.size + 16);
}
// Get last offsets
float lastX = lastOffsets.get(localIndex * 2);
float lastY = lastOffsets.get(localIndex * 2 + 1);
// Calculate new offsets
float x = getLineHeight() * distance * MathUtils.random(-1, 1) * DEFAULT_DISTANCE;
float y = getLineHeight() * distance * MathUtils.random(-1, 1) * DEFAULT_DISTANCE;
// Apply intensity
float normalIntensity = MathUtils.clamp(intensity * DEFAULT_INTENSITY, 0, 1);
x = Interpolation.linear.apply(lastX, x, normalIntensity);
y = Interpolation.linear.apply(lastY, y, normalIntensity);
// Apply fadeout
float fadeout = calculateFadeout();
x *= fadeout;
y *= fadeout;
x = Math.round(x);
y = Math.round(y);
// Store offsets for the next tick
lastOffsets.set(localIndex * 2, x);
lastOffsets.set(localIndex * 2 + 1, y);
// Apply changes
glyph.xoffset += x;
glyph.yoffset += y;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/SickEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.utils.IntArray;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Drips the text in a random pattern. */
public class SickEffect extends Effect {
private static final float DEFAULT_FREQUENCY = 50f;
private static final float DEFAULT_DISTANCE = .125f;
private static final float DEFAULT_INTENSITY = 1f;
public float distance = 1; // How far the glyphs should move
public float intensity = 1; // How fast the glyphs should move
private IntArray indices = new IntArray();
public SickEffect(TypingLabel label, String[] params) {
super(label);
// Distance
if(params.length > 0) {
this.distance = paramAsFloat(params[0], 1);
}
// Intensity
if(params.length > 1) {
this.intensity = paramAsFloat(params[1], 1);
}
// Duration
if(params.length > 2) {
this.duration = paramAsFloat(params[2], -1);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate progress
float progressModifier = (1f / intensity) * DEFAULT_INTENSITY;
float progressOffset = localIndex / DEFAULT_FREQUENCY;
float progress = calculateProgress(progressModifier, -progressOffset, false);
if(progress < .01f && Math.random() > .25f && !indices.contains(localIndex))
indices.add(localIndex);
if(progress > .95f)
indices.removeValue(localIndex);
if(!indices.contains(localIndex) &&
!indices.contains(localIndex - 1) &&
!indices.contains(localIndex - 2) &&
!indices.contains(localIndex + 2) &&
!indices.contains(localIndex + 1))
return;
// Calculate offset
float interpolation = 0;
float split = 0.5f;
if(progress < split) {
interpolation = Interpolation.pow2Out.apply(0, 1, progress / split);
} else {
interpolation = Interpolation.pow2In.apply(1, 0, (progress - split) / (1f - split));
}
float y = getLineHeight() * distance * interpolation * DEFAULT_DISTANCE;
if(indices.contains(localIndex))
y *= 2.15f;
if(indices.contains(localIndex - 1) || indices.contains(localIndex + 1))
y *= 1.35f;
// Calculate fadeout
float fadeout = calculateFadeout();
y *= fadeout;
// Apply changes
glyph.yoffset -= y;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/SlideEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.IntFloatMap;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Moves the text horizontally easing it into the final position. Doesn't repeat itself. */
public class SlideEffect extends Effect {
private static final float DEFAULT_DISTANCE = 2f;
private static final float DEFAULT_INTENSITY = 0.375f;
private float distance = 1; // How much of their height they should move
private float intensity = 1; // How fast the glyphs should move
private boolean elastic = false; // Whether or not the glyphs have an elastic movement
private IntFloatMap timePassedByGlyphIndex = new IntFloatMap();
public SlideEffect(TypingLabel label, String[] params) {
super(label);
// Distance
if(params.length > 0) {
this.distance = paramAsFloat(params[0], 1);
}
// Intensity
if(params.length > 1) {
this.intensity = paramAsFloat(params[1], 1);
}
// Elastic
if(params.length > 2) {
this.elastic = paramAsBoolean(params[2]);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate real intensity
float realIntensity = intensity * (elastic ? 3f : 1f) * DEFAULT_INTENSITY;
// Calculate progress
float timePassed = timePassedByGlyphIndex.getAndIncrement(localIndex, 0, delta);
float progress = MathUtils.clamp(timePassed / realIntensity, 0, 1);
// Calculate offset
Interpolation interpolation = elastic ? Interpolation.swingOut : Interpolation.sine;
float interpolatedValue = interpolation.apply(1, 0, progress);
float x = getLineHeight() * distance * interpolatedValue * DEFAULT_DISTANCE;
// Apply changes
glyph.xoffset += x;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/WaveEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.badlogic.gdx.graphics.g2d.BitmapFont.Glyph;
import com.badlogic.gdx.math.Interpolation;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
/** Moves the text vertically in a sine wave pattern. */
public class WaveEffect extends Effect {
private static final float DEFAULT_FREQUENCY = 15f;
private static final float DEFAULT_DISTANCE = 0.33f;
private static final float DEFAULT_INTENSITY = 0.5f;
private float distance = 1; // How much of their height they should move
private float frequency = 1; // How frequently the wave pattern repeats
private float intensity = 1; // How fast the glyphs should move
public WaveEffect(TypingLabel label, String[] params) {
super(label);
// Distance
if(params.length > 0) {
this.distance = paramAsFloat(params[0], 1);
}
// Frequency
if(params.length > 1) {
this.frequency = paramAsFloat(params[1], 1);
}
// Intensity
if(params.length > 2) {
this.intensity = paramAsFloat(params[2], 1);
}
// Duration
if(params.length > 3) {
this.duration = paramAsFloat(params[3], -1);
}
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate progress
float progressModifier = (1f / intensity) * DEFAULT_INTENSITY;
float normalFrequency = (1f / frequency) * DEFAULT_FREQUENCY;
float progressOffset = localIndex / normalFrequency;
float progress = calculateProgress(progressModifier, progressOffset);
// Calculate offset
float y = getLineHeight() * distance * Interpolation.sine.apply(-1, 1, progress) * DEFAULT_DISTANCE;
// Calculate fadeout
float fadeout = calculateFadeout();
y *= fadeout;
// Apply changes
glyph.yoffset += y;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/effects/WindEffect.java
================================================
package com.rafaskoberg.gdx.typinglabel.effects;
import com.rafaskoberg.gdx.typinglabel.Effect;
import com.rafaskoberg.gdx.typinglabel.TypingGlyph;
import com.rafaskoberg.gdx.typinglabel.TypingLabel;
import com.rafaskoberg.gdx.typinglabel.utils.SimplexNoise;
/** Moves the text in a wind pattern. */
public class WindEffect extends Effect {
private static final float DEFAULT_SPACING = 10f;
private static final float DEFAULT_DISTANCE = 0.33f;
private static final float DEFAULT_INTENSITY = 0.375f;
private static final float DISTANCE_X_RATIO = 1.5f;
private static final float DISTANCE_Y_RATIO = 1.0f;
private static final float IDEAL_DELTA = 60f;
private SimplexNoise noise = new SimplexNoise(1, 0.5f, 1f);
private float noiseCursorX = 0;
private float noiseCursorY = 0;
private float distanceX = 1; // How much of their line height glyphs should move in the X axis
private float distanceY = 1; // How much of their line height glyphs should move in the Y axis
private float spacing = 1; // How much space there should be between waves
private float intensity = 1; // How strong the wind should be
public WindEffect(TypingLabel label, String[] params) {
super(label);
// Distance X
if(params.length > 0) {
this.distanceX = paramAsFloat(params[0], 1);
}
// Distance Y
if(params.length > 1) {
this.distanceY = paramAsFloat(params[1], 1);
}
// Spacing
if(params.length > 2) {
this.spacing = paramAsFloat(params[2], 1);
}
// Intensity
if(params.length > 3) {
this.intensity = paramAsFloat(params[3], 1);
}
// Duration
if(params.length > 4) {
this.duration = paramAsFloat(params[4], -1);
}
}
@Override
public void update(float delta) {
super.update(delta);
// Update noise cursor
float changeAmount = 0.1f * intensity * DEFAULT_INTENSITY * delta * IDEAL_DELTA;
noiseCursorX += changeAmount;
noiseCursorY += changeAmount;
}
@Override
protected void onApply(TypingGlyph glyph, int localIndex, float delta) {
// Calculate progress
float progressModifier = DEFAULT_INTENSITY / intensity;
float normalSpacing = DEFAULT_SPACING / spacing;
float progressOffset = localIndex / normalSpacing;
float progress = calculateProgress(progressModifier, progressOffset);
// Calculate noise
float indexOffset = localIndex * 0.05f * spacing;
float noiseX = noise.getNoise(noiseCursorX + indexOffset, 0);
float noiseY = noise.getNoise(0, noiseCursorY + indexOffset);
// Calculate offset
float lineHeight = getLineHeight();
float x = lineHeight * noiseX * progress * distanceX * DISTANCE_X_RATIO * DEFAULT_DISTANCE;
float y = lineHeight * noiseY * progress * distanceY * DISTANCE_Y_RATIO * DEFAULT_DISTANCE;
// Calculate fadeout
float fadeout = calculateFadeout();
x *= fadeout;
y *= fadeout;
// Add flag effect to X offset
x = Math.abs(x) * -Math.signum(distanceX);
// Apply changes
glyph.xoffset += x;
glyph.yoffset += y;
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/utils/ColorUtils.java
================================================
/*
* Copyright 2014-2017 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Utility class borrowed from Vis-UI.
*/
package com.rafaskoberg.gdx.typinglabel.utils;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.MathUtils;
/**
* Utilities for converting between RGB and HSV color systems.
*
* @author Kotcrab
* @since 0.6.0
*/
public class ColorUtils {
/**
* Converts HSV to RGB
*
* @param h hue 0-360
* @param s saturation 0-100
* @param v value 0-100
* @param alpha 0-1
* @return RGB values in LibGDX {@link Color} class
*/
public static Color HSVtoRGB(float h, float s, float v, float alpha) {
Color c = HSVtoRGB(h, s, v);
c.a = alpha;
return c;
}
/**
* Converts HSV color system to RGB
*
* @param h hue 0-360
* @param s saturation 0-100
* @param v value 0-100
* @return RGB values in LibGDX {@link Color} class
*/
public static Color HSVtoRGB(float h, float s, float v) {
Color c = new Color(1, 1, 1, 1);
HSVtoRGB(h, s, v, c);
return c;
}
/**
* Converts HSV color system to RGB
*
* @param h hue 0-360
* @param s saturation 0-100
* @param v value 0-100
* @param targetColor color that result will be stored in
* @return targetColor
*/
public static Color HSVtoRGB(float h, float s, float v, Color targetColor) {
if(h >= 360) h = 359.999f;
float r, g, b;
int i;
float f, p, q, t;
h = (float) Math.max(0.0, Math.min(360.0, h));
s = (float) Math.max(0.0, Math.min(100.0, s));
v = (float) Math.max(0.0, Math.min(100.0, v));
s /= 100;
v /= 100;
h /= 60;
i = MathUtils.floor(h);
f = h - i;
p = v * (1 - s);
q = v * (1 - s * f);
t = v * (1 - s * (1 - f));
switch(i) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
default:
r = v;
g = p;
b = q;
}
targetColor.set(r, g, b, targetColor.a);
return targetColor;
}
/**
* Converts {@link Color} to HSV color system
*
* @return 3 element int array with hue (0-360), saturation (0-100) and value (0-100)
*/
public static int[] RGBtoHSV(Color c) {
return RGBtoHSV(c.r, c.g, c.b);
}
/**
* Converts RGB to HSV color system
*
* @param r red 0-1
* @param g green 0-1
* @param b blue 0-1
* @return 3 element int array with hue (0-360), saturation (0-100) and value (0-100)
*/
public static int[] RGBtoHSV(float r, float g, float b) {
float h, s, v;
float min, max, delta;
min = Math.min(Math.min(r, g), b);
max = Math.max(Math.max(r, g), b);
v = max;
delta = max - min;
if(max != 0)
s = delta / max;
else {
s = 0;
h = 0;
return new int[]{MathUtils.round(h), MathUtils.round(s), MathUtils.round(v)};
}
if(delta == 0)
h = 0;
else {
if(r == max)
h = (g - b) / delta;
else if(g == max)
h = 2 + (b - r) / delta;
else
h = 4 + (r - g) / delta;
}
h *= 60;
if(h < 0)
h += 360;
s *= 100;
v *= 100;
return new int[]{MathUtils.round(h), MathUtils.round(s), MathUtils.round(v)};
}
}
================================================
FILE: src/main/java/com/rafaskoberg/gdx/typinglabel/utils/SimplexNoise.java
================================================
package com.rafaskoberg.gdx.typinglabel.utils;
import com.badlogic.gdx.math.MathUtils;
/**
* A speed-improved simplex noise algorithm for 2D, 3D and 4D in Java.
*
* Based on example code by Stefan Gustavson (stegu@itn.liu.se). Optimisations by Peter Eastman
* (peastman@drizzle.stanford.edu). Better rank ordering method by Stefan Gustavson in 2012.
*
* This could be speeded up even further, but it's useful as it is.
*