repo_name
stringclasses 5
values | pr_number
int64 1.52k
15.5k
| pr_title
stringlengths 8
143
| pr_description
stringlengths 0
10.2k
| author
stringlengths 3
18
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 11
10.2k
| filepath
stringlengths 6
220
| before_content
stringlengths 0
597M
| after_content
stringlengths 0
597M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-setup/res/com/badlogic/gdx/setup/resources/core/build.gradle | sourceCompatibility = 1.7
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
sourceSets.main.java.srcDirs = [ "src/" ]
eclipse.project.name = appName + "-core"
| sourceCompatibility = 1.8
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
sourceSets.main.java.srcDirs = [ "src/" ]
eclipse.project.name = appName + "-core"
| 1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-setup/res/com/badlogic/gdx/setup/resources/html/build.gradle | gwt {
gwtVersion='%GWT_VERSION%' // Should match the gwt version used for building the gwt backend
maxHeapSize="1G" // Default 256m is not enough for gwt compiler. GWT is HUNGRY
minHeapSize="1G"
src = files(file("src/")) // Needs to be in front of "modules" below.
modules '%PACKAGE%.GdxDefinition'
devModules '%PACKAGE%.GdxDefinitionSuperdev'
project.webAppDirName = 'webapp'
compiler {
strict = true;
disableCastChecking = true;
}
}
import org.docstr.gradle.plugins.gwt.GwtSuperDev
import org.akhikhl.gretty.AppBeforeIntegrationTestTask
gretty.httpPort = 8080
gretty.resourceBase = project.buildDir.path + "/gwt/draftOut"
gretty.contextPath = "/"
gretty.portPropertiesFileName = "TEMP_PORTS.properties"
tasks.register('startHttpServer') {
dependsOn draftCompileGwt
doFirst {
copy {
from "webapp"
into gretty.resourceBase
}
copy {
from "war"
into gretty.resourceBase
}
}
}
task beforeRun(type: AppBeforeIntegrationTestTask, dependsOn: startHttpServer) {
// The next line allows ports to be reused instead of
// needing a process to be manually terminated.
file("build/TEMP_PORTS.properties").delete()
// Somewhat of a hack; uses Gretty's support for wrapping a task in
// a start and then stop of a Jetty server that serves files while
// also running the SuperDev code server.
integrationTestTask 'superDev'
interactive false
}
tasks.register('superDev', GwtSuperDev) {
dependsOn startHttpServer
doFirst {
gwt.modules = gwt.devModules
}
}
tasks.register('dist') {
dependsOn clean, compileGwt
doLast {
file("build/dist").mkdirs()
copy {
from "build/gwt/out"
into "build/dist"
}
copy {
from "webapp"
into "build/dist"
}
copy {
from "war"
into "build/dist"
}
}
}
tasks.register('addSource') {
doLast {
sourceSets.main.compileClasspath += files(project(':core').sourceSets.main.allJava.srcDirs)
}
}
tasks.compileGwt.dependsOn(addSource)
tasks.draftCompileGwt.dependsOn(addSource)
tasks.checkGwt.dependsOn(addSource)
sourceCompatibility = 1.7
sourceSets.main.java.srcDirs = [ "src/" ]
eclipse.project.name = appName + "-html"
| gwt {
gwtVersion='%GWT_VERSION%' // Should match the gwt version used for building the gwt backend
maxHeapSize="1G" // Default 256m is not enough for gwt compiler. GWT is HUNGRY
minHeapSize="1G"
src = files(file("src/")) // Needs to be in front of "modules" below.
modules '%PACKAGE%.GdxDefinition'
devModules '%PACKAGE%.GdxDefinitionSuperdev'
project.webAppDirName = 'webapp'
compiler {
strict = true;
disableCastChecking = true;
}
}
import org.docstr.gradle.plugins.gwt.GwtSuperDev
import org.akhikhl.gretty.AppBeforeIntegrationTestTask
gretty.httpPort = 8080
gretty.resourceBase = project.buildDir.path + "/gwt/draftOut"
gretty.contextPath = "/"
gretty.portPropertiesFileName = "TEMP_PORTS.properties"
tasks.register('startHttpServer') {
dependsOn draftCompileGwt
doFirst {
copy {
from "webapp"
into gretty.resourceBase
}
copy {
from "war"
into gretty.resourceBase
}
}
}
task beforeRun(type: AppBeforeIntegrationTestTask, dependsOn: startHttpServer) {
// The next line allows ports to be reused instead of
// needing a process to be manually terminated.
file("build/TEMP_PORTS.properties").delete()
// Somewhat of a hack; uses Gretty's support for wrapping a task in
// a start and then stop of a Jetty server that serves files while
// also running the SuperDev code server.
integrationTestTask 'superDev'
interactive false
}
tasks.register('superDev', GwtSuperDev) {
dependsOn startHttpServer
doFirst {
gwt.modules = gwt.devModules
}
}
tasks.register('dist') {
dependsOn clean, compileGwt
doLast {
file("build/dist").mkdirs()
copy {
from "build/gwt/out"
into "build/dist"
}
copy {
from "webapp"
into "build/dist"
}
copy {
from "war"
into "build/dist"
}
}
}
tasks.register('addSource') {
doLast {
sourceSets.main.compileClasspath += files(project(':core').sourceSets.main.allJava.srcDirs)
}
}
tasks.compileGwt.dependsOn(addSource)
tasks.draftCompileGwt.dependsOn(addSource)
tasks.checkGwt.dependsOn(addSource)
sourceCompatibility = 1.8
sourceSets.main.java.srcDirs = [ "src/" ]
eclipse.project.name = appName + "-html"
| 1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-setup/res/com/badlogic/gdx/setup/resources/ios/build.gradle | sourceSets.main.java.srcDirs = [ "src/" ]
sourceCompatibility = '1.7'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
ext {
mainClassName = "%PACKAGE%.IOSLauncher"
}
launchIPhoneSimulator.dependsOn build
launchIPadSimulator.dependsOn build
launchIOSDevice.dependsOn build
createIPA.dependsOn build
robovm {
archs = "arm64"
}
eclipse.project.name = appName + "-ios"
| sourceSets.main.java.srcDirs = [ "src/" ]
sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
ext {
mainClassName = "%PACKAGE%.IOSLauncher"
}
launchIPhoneSimulator.dependsOn build
launchIPadSimulator.dependsOn build
launchIOSDevice.dependsOn build
createIPA.dependsOn build
robovm {
archs = "arm64"
}
eclipse.project.name = appName + "-ios"
| 1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-setup/res/com/badlogic/gdx/setup/resources/lwjgl2/build.gradle | sourceCompatibility = 1.7
sourceSets.main.java.srcDirs = [ "src/" ]
sourceSets.main.resources.srcDirs = ["../%ASSET_PATH%"]
project.ext.mainClassName = "%PACKAGE%.DesktopLauncher"
project.ext.assetsDir = new File("../%ASSET_PATH%")
tasks.register('run', JavaExec) {
dependsOn classes
mainClass = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
}
tasks.register('debug', JavaExec) {
dependsOn classes
mainClass = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
debug = true
}
tasks.register('dist', Jar) {
manifest {
attributes 'Main-Class': project.mainClassName
}
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
with jar
}
dist.dependsOn classes
eclipse.project.name = appName + "-legacy_desktop"
| sourceCompatibility = 1.8
sourceSets.main.java.srcDirs = [ "src/" ]
sourceSets.main.resources.srcDirs = ["../%ASSET_PATH%"]
project.ext.mainClassName = "%PACKAGE%.DesktopLauncher"
project.ext.assetsDir = new File("../%ASSET_PATH%")
tasks.register('run', JavaExec) {
dependsOn classes
mainClass = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
}
tasks.register('debug', JavaExec) {
dependsOn classes
mainClass = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
debug = true
}
tasks.register('dist', Jar) {
manifest {
attributes 'Main-Class': project.mainClassName
}
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
with jar
}
dist.dependsOn classes
eclipse.project.name = appName + "-legacy_desktop"
| 1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-setup/src/com/badlogic/gdx/setup/GdxSetupUI.java | /*******************************************************************************
* Copyright 2014 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.
******************************************************************************/
package com.badlogic.gdx.setup;
import static java.awt.GridBagConstraints.BOTH;
import static java.awt.GridBagConstraints.CENTER;
import static java.awt.GridBagConstraints.EAST;
import static java.awt.GridBagConstraints.HORIZONTAL;
import static java.awt.GridBagConstraints.NONE;
import static java.awt.GridBagConstraints.NORTH;
import static java.awt.GridBagConstraints.NORTHEAST;
import static java.awt.GridBagConstraints.NORTHWEST;
import static java.awt.GridBagConstraints.VERTICAL;
import static java.awt.GridBagConstraints.WEST;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import com.badlogic.gdx.setup.DependencyBank.ProjectDependency;
import com.badlogic.gdx.setup.DependencyBank.ProjectType;
import com.badlogic.gdx.setup.Executor.CharCallback;
@SuppressWarnings("serial")
public class GdxSetupUI extends JFrame {
// DependencyBank dependencyBank;
ProjectBuilder builder;
List<ProjectType> modules = new ArrayList<ProjectType>();
List<Dependency> dependencies = new ArrayList<Dependency>();
UI ui = new UI();
static Point point = new Point();
static SetupPreferences prefs = new SetupPreferences();
public GdxSetupUI () {
setTitle("libGDX Project Generator");
setLayout(new BorderLayout());
add(ui, BorderLayout.CENTER);
setSize(620, 720);
setLocationRelativeTo(null);
setUndecorated(true);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
public void mousePressed (MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged (MouseEvent e) {
Point p = getLocation();
setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
}
});
setVisible(true);
builder = new ProjectBuilder(new DependencyBank());
modules.add(ProjectType.CORE);
dependencies.add(builder.bank.getDependency(ProjectDependency.GDX));
}
void generate () {
final String name = ui.form.nameText.getText().trim();
if (name.length() == 0) {
JOptionPane.showMessageDialog(this, "Please enter a project name.");
return;
}
final String pack = ui.form.packageText.getText().trim();
if (pack.length() == 0) {
JOptionPane.showMessageDialog(this, "Please enter a package name.");
return;
}
Pattern pattern = Pattern.compile("[a-z][a-z0-9_]*(\\.[a-z0-9_]+)+[0-9a-z_]");
Matcher matcher = pattern.matcher(pack);
boolean matches = matcher.matches();
if (!matches) {
JOptionPane.showMessageDialog(this, "Invalid package name");
return;
}
final String clazz = ui.form.gameClassText.getText().trim();
if (clazz.length() == 0) {
JOptionPane.showMessageDialog(this, "Please enter a game class name.");
return;
}
final Language languageEnum = ui.settings.kotlinBox.isSelected() ? Language.KOTLIN : Language.JAVA;
final String destination = ui.form.destinationText.getText().trim();
if (destination.length() == 0) {
JOptionPane.showMessageDialog(this, "Please enter a destination directory.");
return;
}
final String assetPath;
if (ui.settings.oldAssetsBox.isSelected()) {
assetPath = modules.contains(ProjectType.ANDROID) ? "android/assets" : "core/assets";
} else {
assetPath = GdxSetup.DEFAULT_ASSET_PATH;
}
final String sdkLocation = ui.form.sdkLocationText.getText().trim();
if (sdkLocation.length() == 0 && modules.contains(ProjectType.ANDROID)) {
JOptionPane.showMessageDialog(this, "Please enter your Android SDK's path");
return;
}
if (!GdxSetup.isSdkLocationValid(sdkLocation) && modules.contains(ProjectType.ANDROID)) {
JOptionPane.showMessageDialog(this,
"Your Android SDK path doesn't contain an SDK! Please install the Android SDK, including all platforms and build tools!");
return;
}
if (modules.contains(ProjectType.HTML) && !languageEnum.gwtSupported) {
JOptionPane.showMessageDialog(this, "HTML sub-projects are not supported by the selected programming language.");
ui.form.gwtCheckBox.setSelected(false);
modules.remove(ProjectType.HTML);
}
if (modules.contains(ProjectType.ANDROID)) {
if (!GdxSetup.isSdkUpToDate(sdkLocation)) {
File sdkLocationFile = new File(sdkLocation);
try { // give them a poke in the right direction
if (System.getProperty("os.name").contains("Windows")) {
String replaced = sdkLocation.replace("\\", "\\\\");
Runtime.getRuntime().exec("\"" + replaced + "\\SDK Manager.exe\"");
} else {
File sdkManager = new File(sdkLocation, "tools/android");
Runtime.getRuntime().exec(new String[] {sdkManager.getAbsolutePath(), "sdk"});
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
}
if (!GdxSetup.isEmptyDirectory(destination)) {
int value = JOptionPane.showConfirmDialog(this, "The destination is not empty, do you want to overwrite?", "Warning!",
JOptionPane.YES_NO_OPTION);
if (value != 0) {
return;
}
}
List<String> incompatList = builder.buildProject(modules, dependencies);
if (incompatList.size() == 0) {
try {
builder.build(languageEnum);
} catch (IOException e) {
e.printStackTrace();
}
} else {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String subIncompat : incompatList) {
JLabel label = new JLabel(subIncompat);
label.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(label);
}
JLabel infoLabel = new JLabel(
"<html><br><br>The project can be generated, but you wont be able to use these extensions in the respective sub modules<br>Please see the link to learn about extensions</html>");
infoLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(infoLabel);
JEditorPane pane = new JEditorPane("text/html",
"<a href=\"https://libgdx.com/wiki/articles/dependency-management-with-gradle\">Dependency Management</a>");
pane.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate (HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) try {
Desktop.getDesktop().browse(new URI(e.getURL().toString()));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
});
pane.setEditable(false);
pane.setOpaque(false);
pane.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(pane);
Object[] options = {"Yes, build it!", "No, I'll change my extensions"};
int value = JOptionPane.showOptionDialog(null, panel, "Extension Incompatibilities", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, null);
if (value != 0) {
return;
} else {
try {
builder.build(languageEnum);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ui.generateButton.setEnabled(false);
new Thread() {
public void run () {
log("Generating app in " + destination);
new GdxSetup().build(builder, destination, name, pack, clazz, languageEnum, assetPath, sdkLocation,
new CharCallback() {
@Override
public void character (char c) {
log(c);
}
}, ui.settings.getGradleArgs());
log("Done!");
log("To import in Eclipse: File -> Import -> Gradle -> Existing Gradle Project");
log("To import to Intellij IDEA: File -> Open -> build.gradle");
log("To import to NetBeans: File -> Open Project...");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run () {
ui.generateButton.setEnabled(true);
}
});
}
}.start();
}
void log (final char c) {
EventQueue.invokeLater(new Runnable() {
public void run () {
ui.textArea.append("" + c);
ui.textArea.setCaretPosition(ui.textArea.getDocument().getLength());
}
});
}
void log (final String text) {
EventQueue.invokeLater(new Runnable() {
public void run () {
ui.textArea.append(text + "\n");
ui.textArea.setCaretPosition(ui.textArea.getDocument().getLength());
}
});
}
class UI extends JPanel {
Form form = new Form();
SettingsDialog settings;
SetupButton generateButton = new SetupButton("Generate");
SetupButton advancedButton = new SetupButton("Advanced");
JPanel buttonPanel = new JPanel();
JTextArea textArea = new JTextArea(8, 40);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel title = new JPanel();
JPanel topBar = new JPanel();
JLabel windowLabel = new JLabel(" libGDX Project Generator (" + DependencyBank.libgdxVersion + ")");
JButton exit;
JButton minimize;
JLabel logo;
{
setBackground(new Color(36, 36, 36));
topBar.setBackground(new Color(64, 67, 69));
title.setBackground(new Color(94, 97, 99));
windowLabel.setForeground(new Color(255, 255, 255));
form.setBackground(new Color(36, 36, 36));
for (int i = 0; i < form.getComponents().length; i++) {
Component component = form.getComponents()[i];
if (component instanceof JTextField) {
component.setBackground(new Color(46, 46, 46));
component.setForeground(new Color(255, 255, 255));
Border line = BorderFactory.createEtchedBorder();
Border pad = new EmptyBorder(0, 5, 0, 0);
CompoundBorder compoundBorder = new CompoundBorder(line, pad);
((JComponent)component).setBorder(compoundBorder);
continue;
}
}
buttonPanel.setBackground(new Color(46, 46, 46));
textArea.setBackground(new Color(46, 46, 46));
textArea.setForeground(new Color(255, 255, 255));
Border line = BorderFactory.createLineBorder(Color.DARK_GRAY);
scrollPane.setBorder(line);
try {
BufferedImage exitimg = ImageIO.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/exitup.png"));
BufferedImage minimg = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/minimizeup.png"));
BufferedImage exitimgdown = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/exitdown.png"));
BufferedImage minimgdown = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/minimizedown.png"));
BufferedImage exithover = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/exithover.png"));
BufferedImage minimghover = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/minimizehover.png"));
BufferedImage img = ImageIO.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/logo.png"));
ImageIcon icon = new ImageIcon(img);
ImageIcon exitIcon = new ImageIcon(exitimg);
ImageIcon minIcon = new ImageIcon(minimg);
ImageIcon exitIconDown = new ImageIcon(exitimgdown);
ImageIcon minIconDown = new ImageIcon(minimgdown);
ImageIcon exitIconHover = new ImageIcon(exithover);
ImageIcon minIconHover = new ImageIcon(minimghover);
logo = new JLabel(icon);
exit = new JButton(exitIcon);
minimize = new JButton(minIcon);
exit.setOpaque(false);
exit.setContentAreaFilled(false);
exit.setFocusPainted(false);
exit.setBorderPainted(false);
exit.setPressedIcon(exitIconDown);
exit.setRolloverIcon(exitIconHover);
minimize.setOpaque(false);
minimize.setContentAreaFilled(false);
minimize.setFocusPainted(false);
minimize.setBorderPainted(false);
minimize.setPressedIcon(minIconDown);
minimize.setRolloverIcon(minIconHover);
} catch (IOException e) {
e.printStackTrace();
}
buttonPanel.add(advancedButton);
buttonPanel.add(generateButton);
textArea.setEditable(false);
textArea.setLineWrap(true);
uiLayout();
uiEvents();
settings = new SettingsDialog(form.gwtCheckBox);
titleEvents(minimize, exit);
}
private void titleEvents (JButton minimize, JButton exit) {
minimize.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
setState(ICONIFIED);
}
});
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
dispose();
System.exit(0);
}
});
}
private void uiLayout () {
title.setLayout(new GridLayout(1, 2));
minimize.setPreferredSize(new Dimension(50, 26));
exit.setPreferredSize(new Dimension(50, 26));
title.add(minimize);
title.add(exit);
topBar.setLayout(new GridLayout(1, 1));
topBar.add(windowLabel, new GridBagConstraints(0, 0, 0, 0, 0, 0, NORTHWEST, VERTICAL, new Insets(0, 0, 0, 0), 0, 0));
setLayout(new GridBagLayout());
add(topBar, new GridBagConstraints(0, 0, 0, 0, 0, 0, NORTH, HORIZONTAL, new Insets(0, 0, 0, 100), 0, 10));
add(title, new GridBagConstraints(0, 0, 0, 0, 0, 0, NORTHEAST, NONE, new Insets(0, 0, 0, 0), 0, 0));
add(logo, new GridBagConstraints(0, 0, 1, 1, 1, 0, CENTER, HORIZONTAL, new Insets(40, 6, 6, 6), 0, 0));
add(form, new GridBagConstraints(0, 1, 1, 1, 1, 0, CENTER, HORIZONTAL, new Insets(6, 6, 0, 6), 0, 0));
add(buttonPanel, new GridBagConstraints(0, 2, 1, 1, 0, 0, CENTER, NONE, new Insets(0, 0, 0, 0), 0, 0));
add(scrollPane, new GridBagConstraints(0, 3, 1, 1, 1, 1, CENTER, BOTH, new Insets(6, 6, 6, 6), 0, 0));
}
private void uiEvents () {
advancedButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
settings.showDialog(form, form.gwtCheckBox);
}
});
generateButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
generate();
}
});
}
}
class Form extends JPanel {
ExternalExtensionsDialog externalExtensionsDialog = new ExternalExtensionsDialog(dependencies);
JLabel nameLabel = new JLabel("Project name:");
JTextField nameText = new JTextField("My GDX Game");
JLabel packageLabel = new JLabel("Package name:");
JTextField packageText = new JTextField("com.mygdx.game");
JLabel gameClassLabel = new JLabel("Game class:");
JTextField gameClassText = new JTextField("MyGdxGame");
JLabel destinationLabel = new JLabel("Output folder:");
JTextField destinationText = new JTextField(new File("test").getAbsolutePath());
SetupButton destinationButton = new SetupButton("Browse");
JLabel sdkLocationLabel = new JLabel("Android SDK");
JTextField sdkLocationText = new JTextField(
System.getProperty("os.name").contains("Windows") ? "C:\\Path\\To\\Your\\Sdk" : "/path/to/your/sdk");
SetupButton sdkLocationButton = new SetupButton("Browse");
JPanel subProjectsPanel = new JPanel(new GridLayout());
JLabel projectsLabel = new JLabel("Supported Platforms");
JLabel extensionsLabel = new JLabel("Official Extensions");
List<JPanel> extensionsPanels = new ArrayList<JPanel>();
SetupButton showMoreExtensionsButton = new SetupButton("Show Third-Party Extensions");
SetupCheckBox gwtCheckBox;
{
uiLayout();
uiEvents();
uiStyle();
}
private void uiStyle () {
nameText.setCaretColor(Color.WHITE);
packageText.setCaretColor(Color.WHITE);
gameClassText.setCaretColor(Color.WHITE);
destinationText.setCaretColor(Color.WHITE);
sdkLocationText.setCaretColor(Color.WHITE);
nameLabel.setForeground(Color.WHITE);
packageLabel.setForeground(Color.WHITE);
gameClassLabel.setForeground(Color.WHITE);
destinationLabel.setForeground(Color.WHITE);
sdkLocationLabel.setForeground(Color.WHITE);
sdkLocationText.setDisabledTextColor(Color.GRAY);
projectsLabel.setForeground(new Color(235, 70, 61));
extensionsLabel.setForeground(new Color(235, 70, 61));
subProjectsPanel.setOpaque(true);
subProjectsPanel.setBackground(new Color(46, 46, 46));
for (JPanel extensionPanel : extensionsPanels) {
extensionPanel.setOpaque(true);
extensionPanel.setBackground(new Color(46, 46, 46));
}
nameLabel.setToolTipText("The name of the application used in gradle");
packageLabel.setToolTipText("The package name of the application");
gameClassLabel.setToolTipText("The name of the main class implementing ApplicationListener");
destinationLabel.setToolTipText("The root directory of the project; will be created if it does not exist");
sdkLocationLabel.setToolTipText("The location of your Android SDK");
}
private void uiLayout () {
setLayout(new GridBagLayout());
add(nameLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 6, 6), 0, 0));
add(nameText, new GridBagConstraints(1, 0, 2, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0));
add(packageLabel, new GridBagConstraints(0, 1, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 6, 6), 0, 0));
add(packageText, new GridBagConstraints(1, 1, 2, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0));
add(gameClassLabel, new GridBagConstraints(0, 2, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 6, 6), 0, 0));
add(gameClassText, new GridBagConstraints(1, 2, 2, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0));
add(destinationLabel, new GridBagConstraints(0, 3, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 0, 6), 0, 0));
add(destinationText, new GridBagConstraints(1, 3, 1, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
add(destinationButton, new GridBagConstraints(2, 3, 1, 1, 0, 0, CENTER, NONE, new Insets(0, 6, 0, 0), 0, 0));
if (System.getenv("ANDROID_HOME") != null) {
sdkLocationText.setText(System.getenv("ANDROID_HOME"));
}
if (prefs.getString("ANDROID_HOME", null) != null) {
sdkLocationText.setText(prefs.getString("ANDROID_HOME"));
}
add(sdkLocationLabel, new GridBagConstraints(0, 4, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 0, 6), 0, 0));
add(sdkLocationText, new GridBagConstraints(1, 4, 1, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
add(sdkLocationButton, new GridBagConstraints(2, 4, 1, 1, 0, 0, CENTER, NONE, new Insets(0, 6, 0, 0), 0, 0));
for (final ProjectType projectType : ProjectType.values()) {
if (projectType.equals(ProjectType.CORE)) {
continue;
}
if (projectType.equals(ProjectType.LWJGL2)) {
continue; // LWJGL 2 projects can only be built via command line
}
SetupCheckBox checkBox = new SetupCheckBox(projectType.getDisplayName());
if (projectType == ProjectType.HTML) {
gwtCheckBox = checkBox;
}
modules.add(projectType);
checkBox.setSelected(true);
subProjectsPanel.add(checkBox);
checkBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged (ItemEvent e) {
SetupCheckBox box = (SetupCheckBox)e.getSource();
if (projectType.equals(ProjectType.ANDROID)) {
sdkLocationText.setEnabled(box.isSelected());
}
if (box.isSelected()) {
modules.add(projectType);
} else {
if (modules.contains(projectType)) {
modules.remove(projectType);
}
}
}
});
}
add(projectsLabel, new GridBagConstraints(0, 6, 1, 1, 0, 0, WEST, WEST, new Insets(20, 0, 0, 0), 0, 0));
add(subProjectsPanel, new GridBagConstraints(0, 7, 3, 1, 0, 0, CENTER, HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
int depCounter = 0;
for (int row = 0; row <= (ProjectDependency.values().length / 5); row++) {
JPanel extensionPanel = new JPanel(new GridLayout(1, 5));
while (depCounter < ProjectDependency.values().length) {
if (ProjectDependency.values()[depCounter] != null) {
final ProjectDependency projDep = ProjectDependency.values()[depCounter];
if (projDep.equals(ProjectDependency.GDX)) {
depCounter++;
continue;
}
SetupCheckBox depCheckBox = new SetupCheckBox(
projDep.name().substring(0, 1) + projDep.name().substring(1, projDep.name().length()).toLowerCase());
depCheckBox.setToolTipText(projDep.getDescription());
extensionPanel.add(depCheckBox);
depCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged (ItemEvent e) {
SetupCheckBox box = (SetupCheckBox)e.getSource();
if (box.isSelected()) {
dependencies.add(builder.bank.getDependency(projDep));
} else {
if (dependencies.contains(builder.bank.getDependency(projDep))) {
dependencies.remove(builder.bank.getDependency(projDep));
}
}
}
});
if (depCounter % 5 == 0) {
depCounter++;
break;
}
depCounter++;
}
}
for (int left = ((depCounter - 1) % 5); left > 1; left--) {
extensionPanel.add(Box.createHorizontalBox());
}
extensionsPanels.add(extensionPanel);
}
add(extensionsLabel, new GridBagConstraints(0, 8, 1, 1, 0, 0, WEST, WEST, new Insets(10, 0, 0, 0), 0, 0));
int rowCounter = 9;
for (JPanel extensionsPanel : extensionsPanels) {
add(extensionsPanel,
new GridBagConstraints(0, rowCounter, 3, 1, 0, 0, CENTER, HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
rowCounter++;
}
add(showMoreExtensionsButton, new GridBagConstraints(0, 12, 0, 1, 0, 0, CENTER, WEST, new Insets(10, 0, 10, 0), 0, 0));
}
File getDirectory (String dialogTitle) {
if (System.getProperty("os.name").contains("Mac")) {
System.setProperty("apple.awt.fileDialogForDirectories", "true");
FileDialog dialog = new FileDialog(GdxSetupUI.this, dialogTitle, FileDialog.LOAD);
dialog.setVisible(true);
String name = dialog.getFile();
String dir = dialog.getDirectory();
if (name == null || dir == null) return null;
return new File(dialog.getDirectory(), dialog.getFile());
} else {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogTitle(dialogTitle);
int result = chooser.showOpenDialog(GdxSetupUI.this);
if (result == JFileChooser.APPROVE_OPTION) {
File dir = chooser.getSelectedFile();
if (dir == null) return null;
if (dir.getAbsolutePath().trim().length() == 0) return null;
return dir;
} else {
return null;
}
}
}
private void uiEvents () {
destinationButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
File path = getDirectory("Choose destination");
if (path != null) {
destinationText.setText(path.getAbsolutePath());
}
}
});
sdkLocationButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
File path = getDirectory("Choose Android SDK");
if (path != null) {
sdkLocationText.setText(path.getAbsolutePath());
prefs.putString("ANDROID_HOME", path.getAbsolutePath());
prefs.flush();
}
}
});
showMoreExtensionsButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
externalExtensionsDialog.showDialog(Form.this);
}
});
}
}
public static class SetupCheckBox extends JCheckBox {
static Icon icon;
static Icon iconOver;
static Icon iconPressed;
static Icon iconPressedSelected;
static Icon iconSelected;
static Icon iconOverSelected;
static {
try {
BufferedImage iconImg = getCheckboxImage("checkbox");
BufferedImage iconOverImg = getCheckboxImage("checkboxover");
BufferedImage iconPressedImg = getCheckboxImage("checkboxpressed");
BufferedImage iconPressedSelectedImg = getCheckboxImage("checkboxpressedselected");
BufferedImage iconSelectedImg = getCheckboxImage("checkboxselected");
BufferedImage iconOverSelectedImg = getCheckboxImage("checkboxoverselected");
icon = new ImageIcon(iconImg);
iconOver = new ImageIcon(iconOverImg);
iconPressed = new ImageIcon(iconPressedImg);
iconPressedSelected = new ImageIcon(iconPressedSelectedImg);
iconSelected = new ImageIcon(iconSelectedImg);
iconOverSelected = new ImageIcon(iconOverSelectedImg);
} catch (IOException e) {
e.printStackTrace();
}
}
private static BufferedImage getCheckboxImage (String imageName) throws IOException {
return ImageIO.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/" + imageName + ".png"));
}
SetupCheckBox () {
super();
initUI();
}
SetupCheckBox (String selectName) {
super(selectName);
initUI();
}
private void initUI () {
setOpaque(false);
setBackground(new Color(0, 0, 0));
setForeground(new Color(255, 255, 255));
setFocusPainted(false);
setIcon(icon);
setRolloverIcon(iconOver);
setPressedIcon(iconPressed);
setSelectedIcon(iconSelected);
setRolloverSelectedIcon(iconOverSelected);
}
public Icon getPressedIcon () {
// checkbox is missing 'pressed selected' icon, this allows us to add it
if (isSelected())
return iconPressedSelected;
else
return super.getPressedIcon();
}
}
public static class SetupButton extends JButton {
private Color textColor = Color.WHITE;
private Color backgroundColor = new Color(18, 18, 18);
private Color overColor = new Color(120, 20, 20);
private Color pressedColor = new Color(240, 40, 40);
SetupButton (String buttonTag) {
super(buttonTag);
setBackground(backgroundColor);
setForeground(textColor);
setContentAreaFilled(false);
setFocusPainted(false);
Border line = BorderFactory.createLineBorder(new Color(80, 80, 80));
Border empty = new EmptyBorder(4, 4, 4, 4);
CompoundBorder border = new CompoundBorder(line, empty);
setBorder(border);
}
@Override
protected void paintComponent (Graphics g) {
if (getModel().isPressed()) {
g.setColor(pressedColor);
} else if (getModel().isRollover()) {
g.setColor(overColor);
} else {
g.setColor(getBackground());
}
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
}
public static void main (String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run () {
new GdxSetupUI();
}
});
}
}
| /*******************************************************************************
* Copyright 2014 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.
******************************************************************************/
package com.badlogic.gdx.setup;
import static java.awt.GridBagConstraints.BOTH;
import static java.awt.GridBagConstraints.CENTER;
import static java.awt.GridBagConstraints.EAST;
import static java.awt.GridBagConstraints.HORIZONTAL;
import static java.awt.GridBagConstraints.NONE;
import static java.awt.GridBagConstraints.NORTH;
import static java.awt.GridBagConstraints.NORTHEAST;
import static java.awt.GridBagConstraints.NORTHWEST;
import static java.awt.GridBagConstraints.VERTICAL;
import static java.awt.GridBagConstraints.WEST;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import com.badlogic.gdx.setup.DependencyBank.ProjectDependency;
import com.badlogic.gdx.setup.DependencyBank.ProjectType;
import com.badlogic.gdx.setup.Executor.CharCallback;
@SuppressWarnings("serial")
public class GdxSetupUI extends JFrame {
// DependencyBank dependencyBank;
ProjectBuilder builder;
List<ProjectType> modules = new ArrayList<ProjectType>();
List<Dependency> dependencies = new ArrayList<Dependency>();
UI ui = new UI();
static Point point = new Point();
static SetupPreferences prefs = new SetupPreferences();
public GdxSetupUI () {
setTitle("libGDX Project Generator");
setLayout(new BorderLayout());
add(ui, BorderLayout.CENTER);
setSize(620, 720);
setLocationRelativeTo(null);
setUndecorated(true);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
public void mousePressed (MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged (MouseEvent e) {
Point p = getLocation();
setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
}
});
setVisible(true);
builder = new ProjectBuilder(new DependencyBank());
modules.add(ProjectType.CORE);
dependencies.add(builder.bank.getDependency(ProjectDependency.GDX));
}
void generate () {
final String name = ui.form.nameText.getText().trim();
if (name.length() == 0) {
JOptionPane.showMessageDialog(this, "Please enter a project name.");
return;
}
final String pack = ui.form.packageText.getText().trim();
if (pack.length() == 0) {
JOptionPane.showMessageDialog(this, "Please enter a package name.");
return;
}
Pattern pattern = Pattern.compile("[a-z][a-z0-9_]*(\\.[a-z0-9_]+)+[0-9a-z_]");
Matcher matcher = pattern.matcher(pack);
boolean matches = matcher.matches();
if (!matches) {
JOptionPane.showMessageDialog(this, "Invalid package name");
return;
}
final String clazz = ui.form.gameClassText.getText().trim();
if (clazz.length() == 0) {
JOptionPane.showMessageDialog(this, "Please enter a game class name.");
return;
}
final Language languageEnum = ui.settings.kotlinBox.isSelected() ? Language.KOTLIN : Language.JAVA;
final String destination = ui.form.destinationText.getText().trim();
if (destination.length() == 0) {
JOptionPane.showMessageDialog(this, "Please enter a destination directory.");
return;
}
final String assetPath;
if (ui.settings.oldAssetsBox.isSelected()) {
assetPath = modules.contains(ProjectType.ANDROID) ? "android/assets" : "core/assets";
} else {
assetPath = GdxSetup.DEFAULT_ASSET_PATH;
}
final String sdkLocation = ui.form.sdkLocationText.getText().trim();
if (sdkLocation.length() == 0 && modules.contains(ProjectType.ANDROID)) {
JOptionPane.showMessageDialog(this, "Please enter your Android SDK's path");
return;
}
if (!GdxSetup.isSdkLocationValid(sdkLocation) && modules.contains(ProjectType.ANDROID)) {
JOptionPane.showMessageDialog(this,
"Your Android SDK path doesn't contain an SDK! Please install the Android SDK, including all platforms and build tools!");
return;
}
if (modules.contains(ProjectType.HTML) && !languageEnum.gwtSupported) {
JOptionPane.showMessageDialog(this, "HTML sub-projects are not supported by the selected programming language.");
ui.form.gwtCheckBox.setSelected(false);
modules.remove(ProjectType.HTML);
}
if (modules.contains(ProjectType.IOS)) {
JOptionPane.showMessageDialog(this, "WARNING. iOS has limited support to Java 8 languages features and APIs.");
}
if (modules.contains(ProjectType.ANDROID)) {
if (!GdxSetup.isSdkUpToDate(sdkLocation)) {
File sdkLocationFile = new File(sdkLocation);
try { // give them a poke in the right direction
if (System.getProperty("os.name").contains("Windows")) {
String replaced = sdkLocation.replace("\\", "\\\\");
Runtime.getRuntime().exec("\"" + replaced + "\\SDK Manager.exe\"");
} else {
File sdkManager = new File(sdkLocation, "tools/android");
Runtime.getRuntime().exec(new String[] {sdkManager.getAbsolutePath(), "sdk"});
}
} catch (IOException e) {
e.printStackTrace();
}
return;
}
}
if (!GdxSetup.isEmptyDirectory(destination)) {
int value = JOptionPane.showConfirmDialog(this, "The destination is not empty, do you want to overwrite?", "Warning!",
JOptionPane.YES_NO_OPTION);
if (value != 0) {
return;
}
}
List<String> incompatList = builder.buildProject(modules, dependencies);
if (incompatList.size() == 0) {
try {
builder.build(languageEnum);
} catch (IOException e) {
e.printStackTrace();
}
} else {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String subIncompat : incompatList) {
JLabel label = new JLabel(subIncompat);
label.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(label);
}
JLabel infoLabel = new JLabel(
"<html><br><br>The project can be generated, but you wont be able to use these extensions in the respective sub modules<br>Please see the link to learn about extensions</html>");
infoLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(infoLabel);
JEditorPane pane = new JEditorPane("text/html",
"<a href=\"https://libgdx.com/wiki/articles/dependency-management-with-gradle\">Dependency Management</a>");
pane.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate (HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) try {
Desktop.getDesktop().browse(new URI(e.getURL().toString()));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
});
pane.setEditable(false);
pane.setOpaque(false);
pane.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(pane);
Object[] options = {"Yes, build it!", "No, I'll change my extensions"};
int value = JOptionPane.showOptionDialog(null, panel, "Extension Incompatibilities", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, null);
if (value != 0) {
return;
} else {
try {
builder.build(languageEnum);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ui.generateButton.setEnabled(false);
new Thread() {
public void run () {
log("Generating app in " + destination);
new GdxSetup().build(builder, destination, name, pack, clazz, languageEnum, assetPath, sdkLocation,
new CharCallback() {
@Override
public void character (char c) {
log(c);
}
}, ui.settings.getGradleArgs());
log("Done!");
log("To import in Eclipse: File -> Import -> Gradle -> Existing Gradle Project");
log("To import to Intellij IDEA: File -> Open -> build.gradle");
log("To import to NetBeans: File -> Open Project...");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run () {
ui.generateButton.setEnabled(true);
}
});
}
}.start();
}
void log (final char c) {
EventQueue.invokeLater(new Runnable() {
public void run () {
ui.textArea.append("" + c);
ui.textArea.setCaretPosition(ui.textArea.getDocument().getLength());
}
});
}
void log (final String text) {
EventQueue.invokeLater(new Runnable() {
public void run () {
ui.textArea.append(text + "\n");
ui.textArea.setCaretPosition(ui.textArea.getDocument().getLength());
}
});
}
class UI extends JPanel {
Form form = new Form();
SettingsDialog settings;
SetupButton generateButton = new SetupButton("Generate");
SetupButton advancedButton = new SetupButton("Advanced");
JPanel buttonPanel = new JPanel();
JTextArea textArea = new JTextArea(8, 40);
JScrollPane scrollPane = new JScrollPane(textArea);
JPanel title = new JPanel();
JPanel topBar = new JPanel();
JLabel windowLabel = new JLabel(" libGDX Project Generator (" + DependencyBank.libgdxVersion + ")");
JButton exit;
JButton minimize;
JLabel logo;
{
setBackground(new Color(36, 36, 36));
topBar.setBackground(new Color(64, 67, 69));
title.setBackground(new Color(94, 97, 99));
windowLabel.setForeground(new Color(255, 255, 255));
form.setBackground(new Color(36, 36, 36));
for (int i = 0; i < form.getComponents().length; i++) {
Component component = form.getComponents()[i];
if (component instanceof JTextField) {
component.setBackground(new Color(46, 46, 46));
component.setForeground(new Color(255, 255, 255));
Border line = BorderFactory.createEtchedBorder();
Border pad = new EmptyBorder(0, 5, 0, 0);
CompoundBorder compoundBorder = new CompoundBorder(line, pad);
((JComponent)component).setBorder(compoundBorder);
continue;
}
}
buttonPanel.setBackground(new Color(46, 46, 46));
textArea.setBackground(new Color(46, 46, 46));
textArea.setForeground(new Color(255, 255, 255));
Border line = BorderFactory.createLineBorder(Color.DARK_GRAY);
scrollPane.setBorder(line);
try {
BufferedImage exitimg = ImageIO.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/exitup.png"));
BufferedImage minimg = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/minimizeup.png"));
BufferedImage exitimgdown = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/exitdown.png"));
BufferedImage minimgdown = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/minimizedown.png"));
BufferedImage exithover = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/exithover.png"));
BufferedImage minimghover = ImageIO
.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/minimizehover.png"));
BufferedImage img = ImageIO.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/logo.png"));
ImageIcon icon = new ImageIcon(img);
ImageIcon exitIcon = new ImageIcon(exitimg);
ImageIcon minIcon = new ImageIcon(minimg);
ImageIcon exitIconDown = new ImageIcon(exitimgdown);
ImageIcon minIconDown = new ImageIcon(minimgdown);
ImageIcon exitIconHover = new ImageIcon(exithover);
ImageIcon minIconHover = new ImageIcon(minimghover);
logo = new JLabel(icon);
exit = new JButton(exitIcon);
minimize = new JButton(minIcon);
exit.setOpaque(false);
exit.setContentAreaFilled(false);
exit.setFocusPainted(false);
exit.setBorderPainted(false);
exit.setPressedIcon(exitIconDown);
exit.setRolloverIcon(exitIconHover);
minimize.setOpaque(false);
minimize.setContentAreaFilled(false);
minimize.setFocusPainted(false);
minimize.setBorderPainted(false);
minimize.setPressedIcon(minIconDown);
minimize.setRolloverIcon(minIconHover);
} catch (IOException e) {
e.printStackTrace();
}
buttonPanel.add(advancedButton);
buttonPanel.add(generateButton);
textArea.setEditable(false);
textArea.setLineWrap(true);
uiLayout();
uiEvents();
settings = new SettingsDialog(form.gwtCheckBox);
titleEvents(minimize, exit);
}
private void titleEvents (JButton minimize, JButton exit) {
minimize.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
setState(ICONIFIED);
}
});
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
dispose();
System.exit(0);
}
});
}
private void uiLayout () {
title.setLayout(new GridLayout(1, 2));
minimize.setPreferredSize(new Dimension(50, 26));
exit.setPreferredSize(new Dimension(50, 26));
title.add(minimize);
title.add(exit);
topBar.setLayout(new GridLayout(1, 1));
topBar.add(windowLabel, new GridBagConstraints(0, 0, 0, 0, 0, 0, NORTHWEST, VERTICAL, new Insets(0, 0, 0, 0), 0, 0));
setLayout(new GridBagLayout());
add(topBar, new GridBagConstraints(0, 0, 0, 0, 0, 0, NORTH, HORIZONTAL, new Insets(0, 0, 0, 100), 0, 10));
add(title, new GridBagConstraints(0, 0, 0, 0, 0, 0, NORTHEAST, NONE, new Insets(0, 0, 0, 0), 0, 0));
add(logo, new GridBagConstraints(0, 0, 1, 1, 1, 0, CENTER, HORIZONTAL, new Insets(40, 6, 6, 6), 0, 0));
add(form, new GridBagConstraints(0, 1, 1, 1, 1, 0, CENTER, HORIZONTAL, new Insets(6, 6, 0, 6), 0, 0));
add(buttonPanel, new GridBagConstraints(0, 2, 1, 1, 0, 0, CENTER, NONE, new Insets(0, 0, 0, 0), 0, 0));
add(scrollPane, new GridBagConstraints(0, 3, 1, 1, 1, 1, CENTER, BOTH, new Insets(6, 6, 6, 6), 0, 0));
}
private void uiEvents () {
advancedButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
settings.showDialog(form, form.gwtCheckBox);
}
});
generateButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
generate();
}
});
}
}
class Form extends JPanel {
ExternalExtensionsDialog externalExtensionsDialog = new ExternalExtensionsDialog(dependencies);
JLabel nameLabel = new JLabel("Project name:");
JTextField nameText = new JTextField("My GDX Game");
JLabel packageLabel = new JLabel("Package name:");
JTextField packageText = new JTextField("com.mygdx.game");
JLabel gameClassLabel = new JLabel("Game class:");
JTextField gameClassText = new JTextField("MyGdxGame");
JLabel destinationLabel = new JLabel("Output folder:");
JTextField destinationText = new JTextField(new File("test").getAbsolutePath());
SetupButton destinationButton = new SetupButton("Browse");
JLabel sdkLocationLabel = new JLabel("Android SDK");
JTextField sdkLocationText = new JTextField(
System.getProperty("os.name").contains("Windows") ? "C:\\Path\\To\\Your\\Sdk" : "/path/to/your/sdk");
SetupButton sdkLocationButton = new SetupButton("Browse");
JPanel subProjectsPanel = new JPanel(new GridLayout());
JLabel projectsLabel = new JLabel("Supported Platforms");
JLabel extensionsLabel = new JLabel("Official Extensions");
List<JPanel> extensionsPanels = new ArrayList<JPanel>();
SetupButton showMoreExtensionsButton = new SetupButton("Show Third-Party Extensions");
SetupCheckBox gwtCheckBox;
{
uiLayout();
uiEvents();
uiStyle();
}
private void uiStyle () {
nameText.setCaretColor(Color.WHITE);
packageText.setCaretColor(Color.WHITE);
gameClassText.setCaretColor(Color.WHITE);
destinationText.setCaretColor(Color.WHITE);
sdkLocationText.setCaretColor(Color.WHITE);
nameLabel.setForeground(Color.WHITE);
packageLabel.setForeground(Color.WHITE);
gameClassLabel.setForeground(Color.WHITE);
destinationLabel.setForeground(Color.WHITE);
sdkLocationLabel.setForeground(Color.WHITE);
sdkLocationText.setDisabledTextColor(Color.GRAY);
projectsLabel.setForeground(new Color(235, 70, 61));
extensionsLabel.setForeground(new Color(235, 70, 61));
subProjectsPanel.setOpaque(true);
subProjectsPanel.setBackground(new Color(46, 46, 46));
for (JPanel extensionPanel : extensionsPanels) {
extensionPanel.setOpaque(true);
extensionPanel.setBackground(new Color(46, 46, 46));
}
nameLabel.setToolTipText("The name of the application used in gradle");
packageLabel.setToolTipText("The package name of the application");
gameClassLabel.setToolTipText("The name of the main class implementing ApplicationListener");
destinationLabel.setToolTipText("The root directory of the project; will be created if it does not exist");
sdkLocationLabel.setToolTipText("The location of your Android SDK");
}
private void uiLayout () {
setLayout(new GridBagLayout());
add(nameLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 6, 6), 0, 0));
add(nameText, new GridBagConstraints(1, 0, 2, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0));
add(packageLabel, new GridBagConstraints(0, 1, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 6, 6), 0, 0));
add(packageText, new GridBagConstraints(1, 1, 2, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0));
add(gameClassLabel, new GridBagConstraints(0, 2, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 6, 6), 0, 0));
add(gameClassText, new GridBagConstraints(1, 2, 2, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 6, 0), 0, 0));
add(destinationLabel, new GridBagConstraints(0, 3, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 0, 6), 0, 0));
add(destinationText, new GridBagConstraints(1, 3, 1, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
add(destinationButton, new GridBagConstraints(2, 3, 1, 1, 0, 0, CENTER, NONE, new Insets(0, 6, 0, 0), 0, 0));
if (System.getenv("ANDROID_HOME") != null) {
sdkLocationText.setText(System.getenv("ANDROID_HOME"));
}
if (prefs.getString("ANDROID_HOME", null) != null) {
sdkLocationText.setText(prefs.getString("ANDROID_HOME"));
}
add(sdkLocationLabel, new GridBagConstraints(0, 4, 1, 1, 0, 0, EAST, NONE, new Insets(0, 0, 0, 6), 0, 0));
add(sdkLocationText, new GridBagConstraints(1, 4, 1, 1, 1, 0, CENTER, HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
add(sdkLocationButton, new GridBagConstraints(2, 4, 1, 1, 0, 0, CENTER, NONE, new Insets(0, 6, 0, 0), 0, 0));
for (final ProjectType projectType : ProjectType.values()) {
if (projectType.equals(ProjectType.CORE)) {
continue;
}
if (projectType.equals(ProjectType.LWJGL2)) {
continue; // LWJGL 2 projects can only be built via command line
}
SetupCheckBox checkBox = new SetupCheckBox(projectType.getDisplayName());
if (projectType == ProjectType.HTML) {
gwtCheckBox = checkBox;
}
modules.add(projectType);
checkBox.setSelected(true);
subProjectsPanel.add(checkBox);
checkBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged (ItemEvent e) {
SetupCheckBox box = (SetupCheckBox)e.getSource();
if (projectType.equals(ProjectType.ANDROID)) {
sdkLocationText.setEnabled(box.isSelected());
}
if (box.isSelected()) {
modules.add(projectType);
} else {
if (modules.contains(projectType)) {
modules.remove(projectType);
}
}
}
});
}
add(projectsLabel, new GridBagConstraints(0, 6, 1, 1, 0, 0, WEST, WEST, new Insets(20, 0, 0, 0), 0, 0));
add(subProjectsPanel, new GridBagConstraints(0, 7, 3, 1, 0, 0, CENTER, HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
int depCounter = 0;
for (int row = 0; row <= (ProjectDependency.values().length / 5); row++) {
JPanel extensionPanel = new JPanel(new GridLayout(1, 5));
while (depCounter < ProjectDependency.values().length) {
if (ProjectDependency.values()[depCounter] != null) {
final ProjectDependency projDep = ProjectDependency.values()[depCounter];
if (projDep.equals(ProjectDependency.GDX)) {
depCounter++;
continue;
}
SetupCheckBox depCheckBox = new SetupCheckBox(
projDep.name().substring(0, 1) + projDep.name().substring(1, projDep.name().length()).toLowerCase());
depCheckBox.setToolTipText(projDep.getDescription());
extensionPanel.add(depCheckBox);
depCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged (ItemEvent e) {
SetupCheckBox box = (SetupCheckBox)e.getSource();
if (box.isSelected()) {
dependencies.add(builder.bank.getDependency(projDep));
} else {
if (dependencies.contains(builder.bank.getDependency(projDep))) {
dependencies.remove(builder.bank.getDependency(projDep));
}
}
}
});
if (depCounter % 5 == 0) {
depCounter++;
break;
}
depCounter++;
}
}
for (int left = ((depCounter - 1) % 5); left > 1; left--) {
extensionPanel.add(Box.createHorizontalBox());
}
extensionsPanels.add(extensionPanel);
}
add(extensionsLabel, new GridBagConstraints(0, 8, 1, 1, 0, 0, WEST, WEST, new Insets(10, 0, 0, 0), 0, 0));
int rowCounter = 9;
for (JPanel extensionsPanel : extensionsPanels) {
add(extensionsPanel,
new GridBagConstraints(0, rowCounter, 3, 1, 0, 0, CENTER, HORIZONTAL, new Insets(5, 0, 0, 0), 0, 0));
rowCounter++;
}
add(showMoreExtensionsButton, new GridBagConstraints(0, 12, 0, 1, 0, 0, CENTER, WEST, new Insets(10, 0, 10, 0), 0, 0));
}
File getDirectory (String dialogTitle) {
if (System.getProperty("os.name").contains("Mac")) {
System.setProperty("apple.awt.fileDialogForDirectories", "true");
FileDialog dialog = new FileDialog(GdxSetupUI.this, dialogTitle, FileDialog.LOAD);
dialog.setVisible(true);
String name = dialog.getFile();
String dir = dialog.getDirectory();
if (name == null || dir == null) return null;
return new File(dialog.getDirectory(), dialog.getFile());
} else {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setDialogTitle(dialogTitle);
int result = chooser.showOpenDialog(GdxSetupUI.this);
if (result == JFileChooser.APPROVE_OPTION) {
File dir = chooser.getSelectedFile();
if (dir == null) return null;
if (dir.getAbsolutePath().trim().length() == 0) return null;
return dir;
} else {
return null;
}
}
}
private void uiEvents () {
destinationButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
File path = getDirectory("Choose destination");
if (path != null) {
destinationText.setText(path.getAbsolutePath());
}
}
});
sdkLocationButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent e) {
File path = getDirectory("Choose Android SDK");
if (path != null) {
sdkLocationText.setText(path.getAbsolutePath());
prefs.putString("ANDROID_HOME", path.getAbsolutePath());
prefs.flush();
}
}
});
showMoreExtensionsButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
externalExtensionsDialog.showDialog(Form.this);
}
});
}
}
public static class SetupCheckBox extends JCheckBox {
static Icon icon;
static Icon iconOver;
static Icon iconPressed;
static Icon iconPressedSelected;
static Icon iconSelected;
static Icon iconOverSelected;
static {
try {
BufferedImage iconImg = getCheckboxImage("checkbox");
BufferedImage iconOverImg = getCheckboxImage("checkboxover");
BufferedImage iconPressedImg = getCheckboxImage("checkboxpressed");
BufferedImage iconPressedSelectedImg = getCheckboxImage("checkboxpressedselected");
BufferedImage iconSelectedImg = getCheckboxImage("checkboxselected");
BufferedImage iconOverSelectedImg = getCheckboxImage("checkboxoverselected");
icon = new ImageIcon(iconImg);
iconOver = new ImageIcon(iconOverImg);
iconPressed = new ImageIcon(iconPressedImg);
iconPressedSelected = new ImageIcon(iconPressedSelectedImg);
iconSelected = new ImageIcon(iconSelectedImg);
iconOverSelected = new ImageIcon(iconOverSelectedImg);
} catch (IOException e) {
e.printStackTrace();
}
}
private static BufferedImage getCheckboxImage (String imageName) throws IOException {
return ImageIO.read(GdxSetupUI.class.getResourceAsStream("/com/badlogic/gdx/setup/data/" + imageName + ".png"));
}
SetupCheckBox () {
super();
initUI();
}
SetupCheckBox (String selectName) {
super(selectName);
initUI();
}
private void initUI () {
setOpaque(false);
setBackground(new Color(0, 0, 0));
setForeground(new Color(255, 255, 255));
setFocusPainted(false);
setIcon(icon);
setRolloverIcon(iconOver);
setPressedIcon(iconPressed);
setSelectedIcon(iconSelected);
setRolloverSelectedIcon(iconOverSelected);
}
public Icon getPressedIcon () {
// checkbox is missing 'pressed selected' icon, this allows us to add it
if (isSelected())
return iconPressedSelected;
else
return super.getPressedIcon();
}
}
public static class SetupButton extends JButton {
private Color textColor = Color.WHITE;
private Color backgroundColor = new Color(18, 18, 18);
private Color overColor = new Color(120, 20, 20);
private Color pressedColor = new Color(240, 40, 40);
SetupButton (String buttonTag) {
super(buttonTag);
setBackground(backgroundColor);
setForeground(textColor);
setContentAreaFilled(false);
setFocusPainted(false);
Border line = BorderFactory.createLineBorder(new Color(80, 80, 80));
Border empty = new EmptyBorder(4, 4, 4, 4);
CompoundBorder border = new CompoundBorder(line, empty);
setBorder(border);
}
@Override
protected void paintComponent (Graphics g) {
if (getModel().isPressed()) {
g.setColor(pressedColor);
} else if (getModel().isRollover()) {
g.setColor(overColor);
} else {
g.setColor(getBackground());
}
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
}
public static void main (String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run () {
new GdxSetupUI();
}
});
}
}
| 1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btTriangleInfoMap.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btTriangleInfoMap extends btHashMapInternalShortBtHashIntBtTriangleInfo {
private long swigCPtr;
protected btTriangleInfoMap (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btTriangleInfoMap_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btTriangleInfoMap, normally you should not need this constructor it's intended for low-level usage. */
public btTriangleInfoMap (long cPtr, boolean cMemoryOwn) {
this("btTriangleInfoMap", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btTriangleInfoMap_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btTriangleInfoMap obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btTriangleInfoMap(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setConvexEpsilon (float value) {
CollisionJNI.btTriangleInfoMap_convexEpsilon_set(swigCPtr, this, value);
}
public float getConvexEpsilon () {
return CollisionJNI.btTriangleInfoMap_convexEpsilon_get(swigCPtr, this);
}
public void setPlanarEpsilon (float value) {
CollisionJNI.btTriangleInfoMap_planarEpsilon_set(swigCPtr, this, value);
}
public float getPlanarEpsilon () {
return CollisionJNI.btTriangleInfoMap_planarEpsilon_get(swigCPtr, this);
}
public void setEqualVertexThreshold (float value) {
CollisionJNI.btTriangleInfoMap_equalVertexThreshold_set(swigCPtr, this, value);
}
public float getEqualVertexThreshold () {
return CollisionJNI.btTriangleInfoMap_equalVertexThreshold_get(swigCPtr, this);
}
public void setEdgeDistanceThreshold (float value) {
CollisionJNI.btTriangleInfoMap_edgeDistanceThreshold_set(swigCPtr, this, value);
}
public float getEdgeDistanceThreshold () {
return CollisionJNI.btTriangleInfoMap_edgeDistanceThreshold_get(swigCPtr, this);
}
public void setMaxEdgeAngleThreshold (float value) {
CollisionJNI.btTriangleInfoMap_maxEdgeAngleThreshold_set(swigCPtr, this, value);
}
public float getMaxEdgeAngleThreshold () {
return CollisionJNI.btTriangleInfoMap_maxEdgeAngleThreshold_get(swigCPtr, this);
}
public void setZeroAreaThreshold (float value) {
CollisionJNI.btTriangleInfoMap_zeroAreaThreshold_set(swigCPtr, this, value);
}
public float getZeroAreaThreshold () {
return CollisionJNI.btTriangleInfoMap_zeroAreaThreshold_get(swigCPtr, this);
}
public btTriangleInfoMap () {
this(CollisionJNI.new_btTriangleInfoMap(), true);
}
public int calculateSerializeBufferSize () {
return CollisionJNI.btTriangleInfoMap_calculateSerializeBufferSize(swigCPtr, this);
}
public String serialize (long dataBuffer, btSerializer serializer) {
return CollisionJNI.btTriangleInfoMap_serialize(swigCPtr, this, dataBuffer, btSerializer.getCPtr(serializer), serializer);
}
public void deSerialize (btTriangleInfoMapData data) {
CollisionJNI.btTriangleInfoMap_deSerialize(swigCPtr, this, btTriangleInfoMapData.getCPtr(data), data);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btTriangleInfoMap extends btHashMapInternalShortBtHashIntBtTriangleInfo {
private long swigCPtr;
protected btTriangleInfoMap (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btTriangleInfoMap_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btTriangleInfoMap, normally you should not need this constructor it's intended for low-level usage. */
public btTriangleInfoMap (long cPtr, boolean cMemoryOwn) {
this("btTriangleInfoMap", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btTriangleInfoMap_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btTriangleInfoMap obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btTriangleInfoMap(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setConvexEpsilon (float value) {
CollisionJNI.btTriangleInfoMap_convexEpsilon_set(swigCPtr, this, value);
}
public float getConvexEpsilon () {
return CollisionJNI.btTriangleInfoMap_convexEpsilon_get(swigCPtr, this);
}
public void setPlanarEpsilon (float value) {
CollisionJNI.btTriangleInfoMap_planarEpsilon_set(swigCPtr, this, value);
}
public float getPlanarEpsilon () {
return CollisionJNI.btTriangleInfoMap_planarEpsilon_get(swigCPtr, this);
}
public void setEqualVertexThreshold (float value) {
CollisionJNI.btTriangleInfoMap_equalVertexThreshold_set(swigCPtr, this, value);
}
public float getEqualVertexThreshold () {
return CollisionJNI.btTriangleInfoMap_equalVertexThreshold_get(swigCPtr, this);
}
public void setEdgeDistanceThreshold (float value) {
CollisionJNI.btTriangleInfoMap_edgeDistanceThreshold_set(swigCPtr, this, value);
}
public float getEdgeDistanceThreshold () {
return CollisionJNI.btTriangleInfoMap_edgeDistanceThreshold_get(swigCPtr, this);
}
public void setMaxEdgeAngleThreshold (float value) {
CollisionJNI.btTriangleInfoMap_maxEdgeAngleThreshold_set(swigCPtr, this, value);
}
public float getMaxEdgeAngleThreshold () {
return CollisionJNI.btTriangleInfoMap_maxEdgeAngleThreshold_get(swigCPtr, this);
}
public void setZeroAreaThreshold (float value) {
CollisionJNI.btTriangleInfoMap_zeroAreaThreshold_set(swigCPtr, this, value);
}
public float getZeroAreaThreshold () {
return CollisionJNI.btTriangleInfoMap_zeroAreaThreshold_get(swigCPtr, this);
}
public btTriangleInfoMap () {
this(CollisionJNI.new_btTriangleInfoMap(), true);
}
public int calculateSerializeBufferSize () {
return CollisionJNI.btTriangleInfoMap_calculateSerializeBufferSize(swigCPtr, this);
}
public String serialize (long dataBuffer, btSerializer serializer) {
return CollisionJNI.btTriangleInfoMap_serialize(swigCPtr, this, dataBuffer, btSerializer.getCPtr(serializer), serializer);
}
public void deSerialize (btTriangleInfoMapData data) {
CollisionJNI.btTriangleInfoMap_deSerialize(swigCPtr, this, btTriangleInfoMapData.getCPtr(data), data);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/dynamics/joints/LimitState.java | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.dynamics.joints;
public enum LimitState {
INACTIVE, AT_LOWER, AT_UPPER, EQUAL
}
| /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.dynamics.joints;
public enum LimitState {
INACTIVE, AT_LOWER, AT_UPPER, EQUAL
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btMultiSphereShape.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btMultiSphereShape extends btConvexInternalAabbCachingShape {
private long swigCPtr;
protected btMultiSphereShape (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btMultiSphereShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btMultiSphereShape, normally you should not need this constructor it's intended for low-level usage. */
public btMultiSphereShape (long cPtr, boolean cMemoryOwn) {
this("btMultiSphereShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btMultiSphereShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btMultiSphereShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btMultiSphereShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btMultiSphereShape_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btMultiSphereShape_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btMultiSphereShape_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btMultiSphereShape_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btMultiSphereShape_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btMultiSphereShape_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btMultiSphereShape_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btMultiSphereShape_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btMultiSphereShape (Vector3[] positions, float[] radi, int numSpheres) {
this(CollisionJNI.new_btMultiSphereShape(positions, radi, numSpheres), true);
}
public int getSphereCount () {
return CollisionJNI.btMultiSphereShape_getSphereCount(swigCPtr, this);
}
public Vector3 getSpherePosition (int index) {
return CollisionJNI.btMultiSphereShape_getSpherePosition(swigCPtr, this, index);
}
public float getSphereRadius (int index) {
return CollisionJNI.btMultiSphereShape_getSphereRadius(swigCPtr, this, index);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btMultiSphereShape extends btConvexInternalAabbCachingShape {
private long swigCPtr;
protected btMultiSphereShape (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btMultiSphereShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btMultiSphereShape, normally you should not need this constructor it's intended for low-level usage. */
public btMultiSphereShape (long cPtr, boolean cMemoryOwn) {
this("btMultiSphereShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btMultiSphereShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btMultiSphereShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btMultiSphereShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btMultiSphereShape_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btMultiSphereShape_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btMultiSphereShape_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btMultiSphereShape_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btMultiSphereShape_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btMultiSphereShape_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btMultiSphereShape_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btMultiSphereShape_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btMultiSphereShape (Vector3[] positions, float[] radi, int numSpheres) {
this(CollisionJNI.new_btMultiSphereShape(positions, radi, numSpheres), true);
}
public int getSphereCount () {
return CollisionJNI.btMultiSphereShape_getSphereCount(swigCPtr, this);
}
public Vector3 getSpherePosition (int index) {
return CollisionJNI.btMultiSphereShape_getSpherePosition(swigCPtr, this, index);
}
public float getSphereRadius (int index) {
return CollisionJNI.btMultiSphereShape_getSphereRadius(swigCPtr, this, index);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/DestructionListener.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.physics.box2d;
public interface DestructionListener {
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.physics.box2d;
public interface DestructionListener {
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./gdx/src/com/badlogic/gdx/scenes/scene2d/utils/Cullable.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.utils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Null;
/** Allows a parent to set the area that is visible on a child actor to allow the child to cull when drawing itself. This must
* only be used for actors that are not rotated or scaled.
* @author Nathan Sweet */
public interface Cullable {
/** @param cullingArea The culling area in the child actor's coordinates. */
public void setCullingArea (@Null Rectangle cullingArea);
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.utils;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Null;
/** Allows a parent to set the area that is visible on a child actor to allow the child to cull when drawing itself. This must
* only be used for actors that are not rotated or scaled.
* @author Nathan Sweet */
public interface Cullable {
/** @param cullingArea The culling area in the child actor's coordinates. */
public void setCullingArea (@Null Rectangle cullingArea);
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/extras/com/badlogic/gdx/physics/bullet/extras/DillCreator.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.extras;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
import com.badlogic.gdx.physics.bullet.dynamics.*;
public class DillCreator extends MultiBodyTreeCreator {
private long swigCPtr;
protected DillCreator (final String className, long cPtr, boolean cMemoryOwn) {
super(className, ExtrasJNI.DillCreator_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new DillCreator, normally you should not need this constructor it's intended for low-level usage. */
public DillCreator (long cPtr, boolean cMemoryOwn) {
this("DillCreator", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(ExtrasJNI.DillCreator_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (DillCreator obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
ExtrasJNI.delete_DillCreator(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public DillCreator (int levels) {
this(ExtrasJNI.new_DillCreator(levels), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.extras;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
import com.badlogic.gdx.physics.bullet.dynamics.*;
public class DillCreator extends MultiBodyTreeCreator {
private long swigCPtr;
protected DillCreator (final String className, long cPtr, boolean cMemoryOwn) {
super(className, ExtrasJNI.DillCreator_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new DillCreator, normally you should not need this constructor it's intended for low-level usage. */
public DillCreator (long cPtr, boolean cMemoryOwn) {
this("DillCreator", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(ExtrasJNI.DillCreator_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (DillCreator obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
ExtrasJNI.delete_DillCreator(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public DillCreator (int levels) {
this(ExtrasJNI.new_DillCreator(levels), true);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/DefaultAndroidInput.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnGenericMotionListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.badlogic.gdx.AbstractInput;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20;
import com.badlogic.gdx.utils.Pool;
import java.util.ArrayList;
import java.util.List;
/** An implementation of the {@link Input} interface for Android.
*
* @author mzechner */
/** @author jshapcot */
public class DefaultAndroidInput extends AbstractInput implements AndroidInput {
static class KeyEvent {
static final int KEY_DOWN = 0;
static final int KEY_UP = 1;
static final int KEY_TYPED = 2;
long timeStamp;
int type;
int keyCode;
char keyChar;
}
static class TouchEvent {
static final int TOUCH_DOWN = 0;
static final int TOUCH_UP = 1;
static final int TOUCH_DRAGGED = 2;
static final int TOUCH_SCROLLED = 3;
static final int TOUCH_MOVED = 4;
static final int TOUCH_CANCELLED = 5;
long timeStamp;
int type;
int x;
int y;
int scrollAmountX;
int scrollAmountY;
int button;
int pointer;
}
Pool<KeyEvent> usedKeyEvents = new Pool<KeyEvent>(16, 1000) {
protected KeyEvent newObject () {
return new KeyEvent();
}
};
Pool<TouchEvent> usedTouchEvents = new Pool<TouchEvent>(16, 1000) {
protected TouchEvent newObject () {
return new TouchEvent();
}
};
public static final int NUM_TOUCHES = 20;
ArrayList<OnKeyListener> keyListeners = new ArrayList();
ArrayList<KeyEvent> keyEvents = new ArrayList();
ArrayList<TouchEvent> touchEvents = new ArrayList();
int[] touchX = new int[NUM_TOUCHES];
int[] touchY = new int[NUM_TOUCHES];
int[] deltaX = new int[NUM_TOUCHES];
int[] deltaY = new int[NUM_TOUCHES];
boolean[] touched = new boolean[NUM_TOUCHES];
int[] button = new int[NUM_TOUCHES];
int[] realId = new int[NUM_TOUCHES];
float[] pressure = new float[NUM_TOUCHES];
final boolean hasMultitouch;
private boolean[] justPressedButtons = new boolean[NUM_TOUCHES];
private SensorManager manager;
public boolean accelerometerAvailable = false;
protected final float[] accelerometerValues = new float[3];
public boolean gyroscopeAvailable = false;
protected final float[] gyroscopeValues = new float[3];
private Handler handle;
final Application app;
final Context context;
protected final AndroidTouchHandler touchHandler;
private int sleepTime = 0;
protected final AndroidHaptics haptics;
private boolean compassAvailable = false;
private boolean rotationVectorAvailable = false;
boolean keyboardAvailable;
protected final float[] magneticFieldValues = new float[3];
protected final float[] rotationVectorValues = new float[3];
private float azimuth = 0;
private float pitch = 0;
private float roll = 0;
private boolean justTouched = false;
private InputProcessor processor;
private final AndroidApplicationConfiguration config;
protected final Orientation nativeOrientation;
private long currentEventTimeStamp = 0;
private SensorEventListener accelerometerListener;
private SensorEventListener gyroscopeListener;
private SensorEventListener compassListener;
private SensorEventListener rotationVectorListener;
private final ArrayList<OnGenericMotionListener> genericMotionListeners = new ArrayList();
private final AndroidMouseHandler mouseHandler;
public DefaultAndroidInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
// we hook into View, for LWPs we call onTouch below directly from
// within the AndroidLivewallpaperEngine#onTouchEvent() method.
if (view instanceof View) {
View v = (View)view;
v.setOnKeyListener(this);
v.setOnTouchListener(this);
v.setFocusable(true);
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnGenericMotionListener(this);
}
this.config = config;
this.mouseHandler = new AndroidMouseHandler();
for (int i = 0; i < realId.length; i++)
realId[i] = -1;
handle = new Handler();
this.app = activity;
this.context = context;
this.sleepTime = config.touchSleepTime;
touchHandler = new AndroidTouchHandler();
hasMultitouch = touchHandler.supportsMultitouch(context);
haptics = new AndroidHaptics(context);
int rotation = getRotation();
DisplayMode mode = app.getGraphics().getDisplayMode();
if (((rotation == 0 || rotation == 180) && (mode.width >= mode.height))
|| ((rotation == 90 || rotation == 270) && (mode.width <= mode.height))) {
nativeOrientation = Orientation.Landscape;
} else {
nativeOrientation = Orientation.Portrait;
}
// this is for backward compatibility: libGDX always caught the circle button, original comment:
// circle button on Xperia Play shouldn't need catchBack == true
setCatchKey(Keys.BUTTON_CIRCLE, true);
}
@Override
public float getAccelerometerX () {
return accelerometerValues[0];
}
@Override
public float getAccelerometerY () {
return accelerometerValues[1];
}
@Override
public float getAccelerometerZ () {
return accelerometerValues[2];
}
@Override
public float getGyroscopeX () {
return gyroscopeValues[0];
}
@Override
public float getGyroscopeY () {
return gyroscopeValues[1];
}
@Override
public float getGyroscopeZ () {
return gyroscopeValues[2];
}
@Override
public void getTextInput (TextInputListener listener, String title, String text, String hint) {
getTextInput(listener, title, text, hint, OnscreenKeyboardType.Default);
}
@Override
public void getTextInput (final TextInputListener listener, final String title, final String text, final String hint,
final OnscreenKeyboardType keyboardType) {
handle.post(new Runnable() {
public void run () {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(title);
final EditText input = new EditText(context);
if (keyboardType != OnscreenKeyboardType.Default) {
input.setInputType(getAndroidInputType(keyboardType));
}
input.setHint(hint);
input.setText(text);
input.setSingleLine();
if (keyboardType == OnscreenKeyboardType.Password) {
input.setTransformationMethod(new PasswordTransformationMethod());
}
alert.setView(input);
alert.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() {
public void onClick (DialogInterface dialog, int whichButton) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
listener.input(input.getText().toString());
}
});
}
});
alert.setNegativeButton(context.getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick (DialogInterface dialog, int whichButton) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
listener.canceled();
}
});
}
});
alert.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel (DialogInterface arg0) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
listener.canceled();
}
});
}
});
alert.show();
}
});
}
public static int getAndroidInputType (OnscreenKeyboardType type) {
int inputType;
switch (type) {
case NumberPad:
inputType = InputType.TYPE_CLASS_NUMBER;
break;
case PhonePad:
inputType = InputType.TYPE_CLASS_PHONE;
break;
case Email:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case Password:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
break;
case URI:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
break;
default:
inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
break;
}
return inputType;
}
@Override
public int getMaxPointers () {
return NUM_TOUCHES;
}
@Override
public int getX () {
synchronized (this) {
return touchX[0];
}
}
@Override
public int getY () {
synchronized (this) {
return touchY[0];
}
}
@Override
public int getX (int pointer) {
synchronized (this) {
return touchX[pointer];
}
}
@Override
public int getY (int pointer) {
synchronized (this) {
return touchY[pointer];
}
}
public boolean isTouched (int pointer) {
synchronized (this) {
return touched[pointer];
}
}
@Override
public float getPressure () {
return getPressure(0);
}
@Override
public float getPressure (int pointer) {
return pressure[pointer];
}
@Override
public void setKeyboardAvailable (boolean available) {
this.keyboardAvailable = available;
}
@Override
public boolean isTouched () {
synchronized (this) {
if (hasMultitouch) {
for (int pointer = 0; pointer < NUM_TOUCHES; pointer++) {
if (touched[pointer]) {
return true;
}
}
}
return touched[0];
}
}
public void setInputProcessor (InputProcessor processor) {
synchronized (this) {
this.processor = processor;
}
}
@Override
public void processEvents () {
synchronized (this) {
if (justTouched) {
justTouched = false;
for (int i = 0; i < justPressedButtons.length; i++) {
justPressedButtons[i] = false;
}
}
if (keyJustPressed) {
keyJustPressed = false;
for (int i = 0; i < justPressedKeys.length; i++) {
justPressedKeys[i] = false;
}
}
if (processor != null) {
final InputProcessor processor = this.processor;
int len = keyEvents.size();
for (int i = 0; i < len; i++) {
KeyEvent e = keyEvents.get(i);
currentEventTimeStamp = e.timeStamp;
switch (e.type) {
case KeyEvent.KEY_DOWN:
processor.keyDown(e.keyCode);
keyJustPressed = true;
justPressedKeys[e.keyCode] = true;
break;
case KeyEvent.KEY_UP:
processor.keyUp(e.keyCode);
break;
case KeyEvent.KEY_TYPED:
processor.keyTyped(e.keyChar);
}
usedKeyEvents.free(e);
}
len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent e = touchEvents.get(i);
currentEventTimeStamp = e.timeStamp;
switch (e.type) {
case TouchEvent.TOUCH_DOWN:
processor.touchDown(e.x, e.y, e.pointer, e.button);
justTouched = true;
justPressedButtons[e.button] = true;
break;
case TouchEvent.TOUCH_UP:
processor.touchUp(e.x, e.y, e.pointer, e.button);
break;
case TouchEvent.TOUCH_DRAGGED:
processor.touchDragged(e.x, e.y, e.pointer);
break;
case TouchEvent.TOUCH_CANCELLED:
processor.touchCancelled(e.x, e.y, e.pointer, e.button);
break;
case TouchEvent.TOUCH_MOVED:
processor.mouseMoved(e.x, e.y);
break;
case TouchEvent.TOUCH_SCROLLED:
processor.scrolled(e.scrollAmountX, e.scrollAmountY);
}
usedTouchEvents.free(e);
}
} else {
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent e = touchEvents.get(i);
if (e.type == TouchEvent.TOUCH_DOWN) justTouched = true;
usedTouchEvents.free(e);
}
len = keyEvents.size();
for (int i = 0; i < len; i++) {
usedKeyEvents.free(keyEvents.get(i));
}
}
if (touchEvents.isEmpty()) {
for (int i = 0; i < deltaX.length; i++) {
deltaX[0] = 0;
deltaY[0] = 0;
}
}
keyEvents.clear();
touchEvents.clear();
}
}
boolean requestFocus = true;
@Override
public boolean onTouch (View view, MotionEvent event) {
if (requestFocus && view != null) {
view.setFocusableInTouchMode(true);
view.requestFocus();
requestFocus = false;
}
// synchronized in handler.postTouchEvent()
touchHandler.onTouch(event, this);
if (sleepTime != 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
return true;
}
// TODO Seems unused. Delete when confirmed.
// /** Called in {@link AndroidLiveWallpaperService} on tap
// * @param x
// * @param y */
// public void onTap (int x, int y) {
// postTap(x, y);
// }
//
// /** Called in {@link AndroidLiveWallpaperService} on drop
// * @param x
// * @param y */
// public void onDrop (int x, int y) {
// postTap(x, y);
// }
//
// protected void postTap (int x, int y) {
// synchronized (this) {
// TouchEvent event = usedTouchEvents.obtain();
// event.timeStamp = System.nanoTime();
// event.pointer = 0;
// event.x = x;
// event.y = y;
// event.type = TouchEvent.TOUCH_DOWN;
// touchEvents.add(event);
//
// event = usedTouchEvents.obtain();
// event.timeStamp = System.nanoTime();
// event.pointer = 0;
// event.x = x;
// event.y = y;
// event.type = TouchEvent.TOUCH_UP;
// touchEvents.add(event);
// }
// Gdx.app.getGraphics().requestRendering();
// }
@Override
public boolean onKey (View v, int keyCode, android.view.KeyEvent e) {
for (int i = 0, n = keyListeners.size(); i < n; i++)
if (keyListeners.get(i).onKey(v, keyCode, e)) return true;
// If the key is held sufficiently long that it repeats, then the initial down is followed
// additional key events with ACTION_DOWN and a non-zero value for getRepeatCount().
// We are only interested in the first key down event here and must ignore all others
if (e.getAction() == android.view.KeyEvent.ACTION_DOWN && e.getRepeatCount() > 0) return isCatchKey(keyCode);
synchronized (this) {
KeyEvent event = null;
if (e.getKeyCode() == android.view.KeyEvent.KEYCODE_UNKNOWN && e.getAction() == android.view.KeyEvent.ACTION_MULTIPLE) {
String chars = e.getCharacters();
for (int i = 0; i < chars.length(); i++) {
event = usedKeyEvents.obtain();
event.timeStamp = System.nanoTime();
event.keyCode = 0;
event.keyChar = chars.charAt(i);
event.type = KeyEvent.KEY_TYPED;
keyEvents.add(event);
}
return false;
}
char character = (char)e.getUnicodeChar();
// Android doesn't report a unicode char for back space. hrm...
if (keyCode == 67) character = '\b';
if (e.getKeyCode() < 0 || e.getKeyCode() > Keys.MAX_KEYCODE) {
return false;
}
switch (e.getAction()) {
case android.view.KeyEvent.ACTION_DOWN:
event = usedKeyEvents.obtain();
event.timeStamp = System.nanoTime();
event.keyChar = 0;
event.keyCode = e.getKeyCode();
event.type = KeyEvent.KEY_DOWN;
// Xperia hack for circle key. gah...
if (keyCode == android.view.KeyEvent.KEYCODE_BACK && e.isAltPressed()) {
keyCode = Keys.BUTTON_CIRCLE;
event.keyCode = keyCode;
}
keyEvents.add(event);
if (!pressedKeys[event.keyCode]) {
pressedKeyCount++;
pressedKeys[event.keyCode] = true;
}
break;
case android.view.KeyEvent.ACTION_UP:
long timeStamp = System.nanoTime();
event = usedKeyEvents.obtain();
event.timeStamp = timeStamp;
event.keyChar = 0;
event.keyCode = e.getKeyCode();
event.type = KeyEvent.KEY_UP;
// Xperia hack for circle key. gah...
if (keyCode == android.view.KeyEvent.KEYCODE_BACK && e.isAltPressed()) {
keyCode = Keys.BUTTON_CIRCLE;
event.keyCode = keyCode;
}
keyEvents.add(event);
event = usedKeyEvents.obtain();
event.timeStamp = timeStamp;
event.keyChar = character;
event.keyCode = 0;
event.type = KeyEvent.KEY_TYPED;
keyEvents.add(event);
if (keyCode == Keys.BUTTON_CIRCLE) {
if (pressedKeys[Keys.BUTTON_CIRCLE]) {
pressedKeyCount--;
pressedKeys[Keys.BUTTON_CIRCLE] = false;
}
} else {
if (pressedKeys[e.getKeyCode()]) {
pressedKeyCount--;
pressedKeys[e.getKeyCode()] = false;
}
}
}
app.getGraphics().requestRendering();
}
return isCatchKey(keyCode);
}
@Override
public void setOnscreenKeyboardVisible (final boolean visible) {
setOnscreenKeyboardVisible(visible, OnscreenKeyboardType.Default);
}
@Override
public void setOnscreenKeyboardVisible (final boolean visible, final OnscreenKeyboardType type) {
handle.post(new Runnable() {
public void run () {
InputMethodManager manager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (visible) {
View view = ((AndroidGraphics)app.getGraphics()).getView();
OnscreenKeyboardType tmp = type == null ? OnscreenKeyboardType.Default : type;
if (((GLSurfaceView20)view).onscreenKeyboardType != tmp) {
((GLSurfaceView20)view).onscreenKeyboardType = tmp;
manager.restartInput(view);
}
view.setFocusable(true);
view.setFocusableInTouchMode(true);
manager.showSoftInput(((AndroidGraphics)app.getGraphics()).getView(), 0);
} else {
manager.hideSoftInputFromWindow(((AndroidGraphics)app.getGraphics()).getView().getWindowToken(), 0);
}
}
});
}
@Override
public void vibrate (int milliseconds) {
haptics.vibrate(milliseconds);
}
@Override
public void vibrate (int milliseconds, boolean fallback) {
haptics.vibrate(milliseconds);
}
@Override
public void vibrate (int milliseconds, int amplitude, boolean fallback) {
haptics.vibrate(milliseconds, amplitude, fallback);
}
@Override
public void vibrate (VibrationType vibrationType) {
haptics.vibrate(vibrationType);
}
@Override
public boolean justTouched () {
return justTouched;
}
@Override
public boolean isButtonPressed (int button) {
synchronized (this) {
if (hasMultitouch) {
for (int pointer = 0; pointer < NUM_TOUCHES; pointer++) {
if (touched[pointer] && (this.button[pointer] == button)) {
return true;
}
}
}
return (touched[0] && (this.button[0] == button));
}
}
@Override
public boolean isButtonJustPressed (int button) {
if (button < 0 || button > NUM_TOUCHES) return false;
return justPressedButtons[button];
}
final float[] R = new float[9];
final float[] orientation = new float[3];
private void updateOrientation () {
if (rotationVectorAvailable) {
SensorManager.getRotationMatrixFromVector(R, rotationVectorValues);
} else if (!SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticFieldValues)) {
return; // compass + accelerometer in free fall
}
SensorManager.getOrientation(R, orientation);
azimuth = (float)Math.toDegrees(orientation[0]);
pitch = (float)Math.toDegrees(orientation[1]);
roll = (float)Math.toDegrees(orientation[2]);
}
/** Returns the rotation matrix describing the devices rotation as per
* <a href= "http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[],
* float[], float[])" >SensorManager#getRotationMatrix(float[], float[], float[], float[])</a>. Does not manipulate the matrix
* if the platform does not have an accelerometer and compass, or a rotation vector sensor.
* @param matrix */
public void getRotationMatrix (float[] matrix) {
if (rotationVectorAvailable)
SensorManager.getRotationMatrixFromVector(matrix, rotationVectorValues);
else // compass + accelerometer
SensorManager.getRotationMatrix(matrix, null, accelerometerValues, magneticFieldValues);
}
@Override
public float getAzimuth () {
if (!compassAvailable && !rotationVectorAvailable) return 0;
updateOrientation();
return azimuth;
}
@Override
public float getPitch () {
if (!compassAvailable && !rotationVectorAvailable) return 0;
updateOrientation();
return pitch;
}
@Override
public float getRoll () {
if (!compassAvailable && !rotationVectorAvailable) return 0;
updateOrientation();
return roll;
}
void registerSensorListeners () {
if (config.useAccelerometer) {
manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).isEmpty()) {
accelerometerAvailable = false;
} else {
Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
accelerometerListener = new SensorListener();
accelerometerAvailable = manager.registerListener(accelerometerListener, accelerometer, config.sensorDelay);
}
} else
accelerometerAvailable = false;
if (config.useGyroscope) {
manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
if (manager.getSensorList(Sensor.TYPE_GYROSCOPE).isEmpty()) {
gyroscopeAvailable = false;
} else {
Sensor gyroscope = manager.getSensorList(Sensor.TYPE_GYROSCOPE).get(0);
gyroscopeListener = new SensorListener();
gyroscopeAvailable = manager.registerListener(gyroscopeListener, gyroscope, config.sensorDelay);
}
} else
gyroscopeAvailable = false;
rotationVectorAvailable = false;
if (config.useRotationVectorSensor) {
if (manager == null) manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> rotationVectorSensors = manager.getSensorList(Sensor.TYPE_ROTATION_VECTOR);
if (!rotationVectorSensors.isEmpty()) {
rotationVectorListener = new SensorListener();
for (Sensor sensor : rotationVectorSensors) { // favor AOSP sensor
if (sensor.getVendor().equals("Google Inc.") && sensor.getVersion() == 3) {
rotationVectorAvailable = manager.registerListener(rotationVectorListener, sensor, config.sensorDelay);
break;
}
}
if (!rotationVectorAvailable) rotationVectorAvailable = manager.registerListener(rotationVectorListener,
rotationVectorSensors.get(0), config.sensorDelay);
}
}
if (config.useCompass && !rotationVectorAvailable) {
if (manager == null) manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
if (sensor != null) {
compassAvailable = accelerometerAvailable;
if (compassAvailable) {
compassListener = new SensorListener();
compassAvailable = manager.registerListener(compassListener, sensor, config.sensorDelay);
}
} else {
compassAvailable = false;
}
} else
compassAvailable = false;
Gdx.app.log("AndroidInput", "sensor listener setup");
}
void unregisterSensorListeners () {
if (manager != null) {
if (accelerometerListener != null) {
manager.unregisterListener(accelerometerListener);
accelerometerListener = null;
}
if (gyroscopeListener != null) {
manager.unregisterListener(gyroscopeListener);
gyroscopeListener = null;
}
if (rotationVectorListener != null) {
manager.unregisterListener(rotationVectorListener);
rotationVectorListener = null;
}
if (compassListener != null) {
manager.unregisterListener(compassListener);
compassListener = null;
}
manager = null;
}
Gdx.app.log("AndroidInput", "sensor listener tear down");
}
@Override
public InputProcessor getInputProcessor () {
return this.processor;
}
@Override
public boolean isPeripheralAvailable (Peripheral peripheral) {
if (peripheral == Peripheral.Accelerometer) return accelerometerAvailable;
if (peripheral == Peripheral.Gyroscope) return gyroscopeAvailable;
if (peripheral == Peripheral.Compass) return compassAvailable;
if (peripheral == Peripheral.HardwareKeyboard) return keyboardAvailable;
if (peripheral == Peripheral.OnscreenKeyboard) return true;
if (peripheral == Peripheral.Vibrator) return haptics.hasVibratorAvailable();
if (peripheral == Peripheral.HapticFeedback) return haptics.hasHapticsSupport();
if (peripheral == Peripheral.MultitouchScreen) return hasMultitouch;
if (peripheral == Peripheral.RotationVector) return rotationVectorAvailable;
if (peripheral == Peripheral.Pressure) return true;
return false;
}
public int getFreePointerIndex () {
int len = realId.length;
for (int i = 0; i < len; i++) {
if (realId[i] == -1) return i;
}
pressure = resize(pressure);
realId = resize(realId);
touchX = resize(touchX);
touchY = resize(touchY);
deltaX = resize(deltaX);
deltaY = resize(deltaY);
touched = resize(touched);
button = resize(button);
return len;
}
private int[] resize (int[] orig) {
int[] tmp = new int[orig.length + 2];
System.arraycopy(orig, 0, tmp, 0, orig.length);
return tmp;
}
private boolean[] resize (boolean[] orig) {
boolean[] tmp = new boolean[orig.length + 2];
System.arraycopy(orig, 0, tmp, 0, orig.length);
return tmp;
}
private float[] resize (float[] orig) {
float[] tmp = new float[orig.length + 2];
System.arraycopy(orig, 0, tmp, 0, orig.length);
return tmp;
}
public int lookUpPointerIndex (int pointerId) {
int len = realId.length;
for (int i = 0; i < len; i++) {
if (realId[i] == pointerId) return i;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append(i + ":" + realId[i] + " ");
}
Gdx.app.log("AndroidInput", "Pointer ID lookup failed: " + pointerId + ", " + sb.toString());
return -1;
}
@Override
public int getRotation () {
int orientation = 0;
if (context instanceof Activity) {
orientation = ((Activity)context).getWindowManager().getDefaultDisplay().getRotation();
} else {
orientation = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
}
switch (orientation) {
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90:
return 90;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_270:
return 270;
default:
return 0;
}
}
@Override
public Orientation getNativeOrientation () {
return nativeOrientation;
}
@Override
public void setCursorCatched (boolean catched) {
}
@Override
public boolean isCursorCatched () {
return false;
}
@Override
public int getDeltaX () {
return deltaX[0];
}
@Override
public int getDeltaX (int pointer) {
return deltaX[pointer];
}
@Override
public int getDeltaY () {
return deltaY[0];
}
@Override
public int getDeltaY (int pointer) {
return deltaY[pointer];
}
@Override
public void setCursorPosition (int x, int y) {
}
@Override
public long getCurrentEventTime () {
return currentEventTimeStamp;
}
@Override
public void addKeyListener (OnKeyListener listener) {
keyListeners.add(listener);
}
@Override
public boolean onGenericMotion (View view, MotionEvent event) {
if (mouseHandler.onGenericMotion(event, this)) return true;
for (int i = 0, n = genericMotionListeners.size(); i < n; i++)
if (genericMotionListeners.get(i).onGenericMotion(view, event)) return true;
return false;
}
@Override
public void addGenericMotionListener (OnGenericMotionListener listener) {
genericMotionListeners.add(listener);
}
@Override
public void onPause () {
unregisterSensorListeners();
}
@Override
public void onResume () {
registerSensorListeners();
}
@Override
public void onDreamingStarted () {
registerSensorListeners();
}
@Override
public void onDreamingStopped () {
unregisterSensorListeners();
}
/** Our implementation of SensorEventListener. Because Android doesn't like it when we register more than one Sensor to a
* single SensorEventListener, we add one of these for each Sensor. Could use an anonymous class, but I don't see any harm in
* explicitly defining it here. Correct me if I am wrong. */
private class SensorListener implements SensorEventListener {
public SensorListener () {
}
@Override
public void onAccuracyChanged (Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged (SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if (nativeOrientation == Orientation.Portrait) {
System.arraycopy(event.values, 0, accelerometerValues, 0, accelerometerValues.length);
} else {
accelerometerValues[0] = event.values[1];
accelerometerValues[1] = -event.values[0];
accelerometerValues[2] = event.values[2];
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
System.arraycopy(event.values, 0, magneticFieldValues, 0, magneticFieldValues.length);
}
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
if (nativeOrientation == Orientation.Portrait) {
System.arraycopy(event.values, 0, gyroscopeValues, 0, gyroscopeValues.length);
} else {
gyroscopeValues[0] = event.values[1];
gyroscopeValues[1] = -event.values[0];
gyroscopeValues[2] = event.values[2];
}
}
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
if (nativeOrientation == Orientation.Portrait) {
System.arraycopy(event.values, 0, rotationVectorValues, 0, rotationVectorValues.length);
} else {
rotationVectorValues[0] = event.values[1];
rotationVectorValues[1] = -event.values[0];
rotationVectorValues[2] = event.values[2];
}
}
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnGenericMotionListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.badlogic.gdx.AbstractInput;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20;
import com.badlogic.gdx.utils.Pool;
import java.util.ArrayList;
import java.util.List;
/** An implementation of the {@link Input} interface for Android.
*
* @author mzechner */
/** @author jshapcot */
public class DefaultAndroidInput extends AbstractInput implements AndroidInput {
static class KeyEvent {
static final int KEY_DOWN = 0;
static final int KEY_UP = 1;
static final int KEY_TYPED = 2;
long timeStamp;
int type;
int keyCode;
char keyChar;
}
static class TouchEvent {
static final int TOUCH_DOWN = 0;
static final int TOUCH_UP = 1;
static final int TOUCH_DRAGGED = 2;
static final int TOUCH_SCROLLED = 3;
static final int TOUCH_MOVED = 4;
static final int TOUCH_CANCELLED = 5;
long timeStamp;
int type;
int x;
int y;
int scrollAmountX;
int scrollAmountY;
int button;
int pointer;
}
Pool<KeyEvent> usedKeyEvents = new Pool<KeyEvent>(16, 1000) {
protected KeyEvent newObject () {
return new KeyEvent();
}
};
Pool<TouchEvent> usedTouchEvents = new Pool<TouchEvent>(16, 1000) {
protected TouchEvent newObject () {
return new TouchEvent();
}
};
public static final int NUM_TOUCHES = 20;
ArrayList<OnKeyListener> keyListeners = new ArrayList();
ArrayList<KeyEvent> keyEvents = new ArrayList();
ArrayList<TouchEvent> touchEvents = new ArrayList();
int[] touchX = new int[NUM_TOUCHES];
int[] touchY = new int[NUM_TOUCHES];
int[] deltaX = new int[NUM_TOUCHES];
int[] deltaY = new int[NUM_TOUCHES];
boolean[] touched = new boolean[NUM_TOUCHES];
int[] button = new int[NUM_TOUCHES];
int[] realId = new int[NUM_TOUCHES];
float[] pressure = new float[NUM_TOUCHES];
final boolean hasMultitouch;
private boolean[] justPressedButtons = new boolean[NUM_TOUCHES];
private SensorManager manager;
public boolean accelerometerAvailable = false;
protected final float[] accelerometerValues = new float[3];
public boolean gyroscopeAvailable = false;
protected final float[] gyroscopeValues = new float[3];
private Handler handle;
final Application app;
final Context context;
protected final AndroidTouchHandler touchHandler;
private int sleepTime = 0;
protected final AndroidHaptics haptics;
private boolean compassAvailable = false;
private boolean rotationVectorAvailable = false;
boolean keyboardAvailable;
protected final float[] magneticFieldValues = new float[3];
protected final float[] rotationVectorValues = new float[3];
private float azimuth = 0;
private float pitch = 0;
private float roll = 0;
private boolean justTouched = false;
private InputProcessor processor;
private final AndroidApplicationConfiguration config;
protected final Orientation nativeOrientation;
private long currentEventTimeStamp = 0;
private SensorEventListener accelerometerListener;
private SensorEventListener gyroscopeListener;
private SensorEventListener compassListener;
private SensorEventListener rotationVectorListener;
private final ArrayList<OnGenericMotionListener> genericMotionListeners = new ArrayList();
private final AndroidMouseHandler mouseHandler;
public DefaultAndroidInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
// we hook into View, for LWPs we call onTouch below directly from
// within the AndroidLivewallpaperEngine#onTouchEvent() method.
if (view instanceof View) {
View v = (View)view;
v.setOnKeyListener(this);
v.setOnTouchListener(this);
v.setFocusable(true);
v.setFocusableInTouchMode(true);
v.requestFocus();
v.setOnGenericMotionListener(this);
}
this.config = config;
this.mouseHandler = new AndroidMouseHandler();
for (int i = 0; i < realId.length; i++)
realId[i] = -1;
handle = new Handler();
this.app = activity;
this.context = context;
this.sleepTime = config.touchSleepTime;
touchHandler = new AndroidTouchHandler();
hasMultitouch = touchHandler.supportsMultitouch(context);
haptics = new AndroidHaptics(context);
int rotation = getRotation();
DisplayMode mode = app.getGraphics().getDisplayMode();
if (((rotation == 0 || rotation == 180) && (mode.width >= mode.height))
|| ((rotation == 90 || rotation == 270) && (mode.width <= mode.height))) {
nativeOrientation = Orientation.Landscape;
} else {
nativeOrientation = Orientation.Portrait;
}
// this is for backward compatibility: libGDX always caught the circle button, original comment:
// circle button on Xperia Play shouldn't need catchBack == true
setCatchKey(Keys.BUTTON_CIRCLE, true);
}
@Override
public float getAccelerometerX () {
return accelerometerValues[0];
}
@Override
public float getAccelerometerY () {
return accelerometerValues[1];
}
@Override
public float getAccelerometerZ () {
return accelerometerValues[2];
}
@Override
public float getGyroscopeX () {
return gyroscopeValues[0];
}
@Override
public float getGyroscopeY () {
return gyroscopeValues[1];
}
@Override
public float getGyroscopeZ () {
return gyroscopeValues[2];
}
@Override
public void getTextInput (TextInputListener listener, String title, String text, String hint) {
getTextInput(listener, title, text, hint, OnscreenKeyboardType.Default);
}
@Override
public void getTextInput (final TextInputListener listener, final String title, final String text, final String hint,
final OnscreenKeyboardType keyboardType) {
handle.post(new Runnable() {
public void run () {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle(title);
final EditText input = new EditText(context);
if (keyboardType != OnscreenKeyboardType.Default) {
input.setInputType(getAndroidInputType(keyboardType));
}
input.setHint(hint);
input.setText(text);
input.setSingleLine();
if (keyboardType == OnscreenKeyboardType.Password) {
input.setTransformationMethod(new PasswordTransformationMethod());
}
alert.setView(input);
alert.setPositiveButton(context.getString(android.R.string.ok), new DialogInterface.OnClickListener() {
public void onClick (DialogInterface dialog, int whichButton) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
listener.input(input.getText().toString());
}
});
}
});
alert.setNegativeButton(context.getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick (DialogInterface dialog, int whichButton) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
listener.canceled();
}
});
}
});
alert.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel (DialogInterface arg0) {
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
listener.canceled();
}
});
}
});
alert.show();
}
});
}
public static int getAndroidInputType (OnscreenKeyboardType type) {
int inputType;
switch (type) {
case NumberPad:
inputType = InputType.TYPE_CLASS_NUMBER;
break;
case PhonePad:
inputType = InputType.TYPE_CLASS_PHONE;
break;
case Email:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case Password:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
break;
case URI:
inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
break;
default:
inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
break;
}
return inputType;
}
@Override
public int getMaxPointers () {
return NUM_TOUCHES;
}
@Override
public int getX () {
synchronized (this) {
return touchX[0];
}
}
@Override
public int getY () {
synchronized (this) {
return touchY[0];
}
}
@Override
public int getX (int pointer) {
synchronized (this) {
return touchX[pointer];
}
}
@Override
public int getY (int pointer) {
synchronized (this) {
return touchY[pointer];
}
}
public boolean isTouched (int pointer) {
synchronized (this) {
return touched[pointer];
}
}
@Override
public float getPressure () {
return getPressure(0);
}
@Override
public float getPressure (int pointer) {
return pressure[pointer];
}
@Override
public void setKeyboardAvailable (boolean available) {
this.keyboardAvailable = available;
}
@Override
public boolean isTouched () {
synchronized (this) {
if (hasMultitouch) {
for (int pointer = 0; pointer < NUM_TOUCHES; pointer++) {
if (touched[pointer]) {
return true;
}
}
}
return touched[0];
}
}
public void setInputProcessor (InputProcessor processor) {
synchronized (this) {
this.processor = processor;
}
}
@Override
public void processEvents () {
synchronized (this) {
if (justTouched) {
justTouched = false;
for (int i = 0; i < justPressedButtons.length; i++) {
justPressedButtons[i] = false;
}
}
if (keyJustPressed) {
keyJustPressed = false;
for (int i = 0; i < justPressedKeys.length; i++) {
justPressedKeys[i] = false;
}
}
if (processor != null) {
final InputProcessor processor = this.processor;
int len = keyEvents.size();
for (int i = 0; i < len; i++) {
KeyEvent e = keyEvents.get(i);
currentEventTimeStamp = e.timeStamp;
switch (e.type) {
case KeyEvent.KEY_DOWN:
processor.keyDown(e.keyCode);
keyJustPressed = true;
justPressedKeys[e.keyCode] = true;
break;
case KeyEvent.KEY_UP:
processor.keyUp(e.keyCode);
break;
case KeyEvent.KEY_TYPED:
processor.keyTyped(e.keyChar);
}
usedKeyEvents.free(e);
}
len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent e = touchEvents.get(i);
currentEventTimeStamp = e.timeStamp;
switch (e.type) {
case TouchEvent.TOUCH_DOWN:
processor.touchDown(e.x, e.y, e.pointer, e.button);
justTouched = true;
justPressedButtons[e.button] = true;
break;
case TouchEvent.TOUCH_UP:
processor.touchUp(e.x, e.y, e.pointer, e.button);
break;
case TouchEvent.TOUCH_DRAGGED:
processor.touchDragged(e.x, e.y, e.pointer);
break;
case TouchEvent.TOUCH_CANCELLED:
processor.touchCancelled(e.x, e.y, e.pointer, e.button);
break;
case TouchEvent.TOUCH_MOVED:
processor.mouseMoved(e.x, e.y);
break;
case TouchEvent.TOUCH_SCROLLED:
processor.scrolled(e.scrollAmountX, e.scrollAmountY);
}
usedTouchEvents.free(e);
}
} else {
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent e = touchEvents.get(i);
if (e.type == TouchEvent.TOUCH_DOWN) justTouched = true;
usedTouchEvents.free(e);
}
len = keyEvents.size();
for (int i = 0; i < len; i++) {
usedKeyEvents.free(keyEvents.get(i));
}
}
if (touchEvents.isEmpty()) {
for (int i = 0; i < deltaX.length; i++) {
deltaX[0] = 0;
deltaY[0] = 0;
}
}
keyEvents.clear();
touchEvents.clear();
}
}
boolean requestFocus = true;
@Override
public boolean onTouch (View view, MotionEvent event) {
if (requestFocus && view != null) {
view.setFocusableInTouchMode(true);
view.requestFocus();
requestFocus = false;
}
// synchronized in handler.postTouchEvent()
touchHandler.onTouch(event, this);
if (sleepTime != 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
return true;
}
// TODO Seems unused. Delete when confirmed.
// /** Called in {@link AndroidLiveWallpaperService} on tap
// * @param x
// * @param y */
// public void onTap (int x, int y) {
// postTap(x, y);
// }
//
// /** Called in {@link AndroidLiveWallpaperService} on drop
// * @param x
// * @param y */
// public void onDrop (int x, int y) {
// postTap(x, y);
// }
//
// protected void postTap (int x, int y) {
// synchronized (this) {
// TouchEvent event = usedTouchEvents.obtain();
// event.timeStamp = System.nanoTime();
// event.pointer = 0;
// event.x = x;
// event.y = y;
// event.type = TouchEvent.TOUCH_DOWN;
// touchEvents.add(event);
//
// event = usedTouchEvents.obtain();
// event.timeStamp = System.nanoTime();
// event.pointer = 0;
// event.x = x;
// event.y = y;
// event.type = TouchEvent.TOUCH_UP;
// touchEvents.add(event);
// }
// Gdx.app.getGraphics().requestRendering();
// }
@Override
public boolean onKey (View v, int keyCode, android.view.KeyEvent e) {
for (int i = 0, n = keyListeners.size(); i < n; i++)
if (keyListeners.get(i).onKey(v, keyCode, e)) return true;
// If the key is held sufficiently long that it repeats, then the initial down is followed
// additional key events with ACTION_DOWN and a non-zero value for getRepeatCount().
// We are only interested in the first key down event here and must ignore all others
if (e.getAction() == android.view.KeyEvent.ACTION_DOWN && e.getRepeatCount() > 0) return isCatchKey(keyCode);
synchronized (this) {
KeyEvent event = null;
if (e.getKeyCode() == android.view.KeyEvent.KEYCODE_UNKNOWN && e.getAction() == android.view.KeyEvent.ACTION_MULTIPLE) {
String chars = e.getCharacters();
for (int i = 0; i < chars.length(); i++) {
event = usedKeyEvents.obtain();
event.timeStamp = System.nanoTime();
event.keyCode = 0;
event.keyChar = chars.charAt(i);
event.type = KeyEvent.KEY_TYPED;
keyEvents.add(event);
}
return false;
}
char character = (char)e.getUnicodeChar();
// Android doesn't report a unicode char for back space. hrm...
if (keyCode == 67) character = '\b';
if (e.getKeyCode() < 0 || e.getKeyCode() > Keys.MAX_KEYCODE) {
return false;
}
switch (e.getAction()) {
case android.view.KeyEvent.ACTION_DOWN:
event = usedKeyEvents.obtain();
event.timeStamp = System.nanoTime();
event.keyChar = 0;
event.keyCode = e.getKeyCode();
event.type = KeyEvent.KEY_DOWN;
// Xperia hack for circle key. gah...
if (keyCode == android.view.KeyEvent.KEYCODE_BACK && e.isAltPressed()) {
keyCode = Keys.BUTTON_CIRCLE;
event.keyCode = keyCode;
}
keyEvents.add(event);
if (!pressedKeys[event.keyCode]) {
pressedKeyCount++;
pressedKeys[event.keyCode] = true;
}
break;
case android.view.KeyEvent.ACTION_UP:
long timeStamp = System.nanoTime();
event = usedKeyEvents.obtain();
event.timeStamp = timeStamp;
event.keyChar = 0;
event.keyCode = e.getKeyCode();
event.type = KeyEvent.KEY_UP;
// Xperia hack for circle key. gah...
if (keyCode == android.view.KeyEvent.KEYCODE_BACK && e.isAltPressed()) {
keyCode = Keys.BUTTON_CIRCLE;
event.keyCode = keyCode;
}
keyEvents.add(event);
event = usedKeyEvents.obtain();
event.timeStamp = timeStamp;
event.keyChar = character;
event.keyCode = 0;
event.type = KeyEvent.KEY_TYPED;
keyEvents.add(event);
if (keyCode == Keys.BUTTON_CIRCLE) {
if (pressedKeys[Keys.BUTTON_CIRCLE]) {
pressedKeyCount--;
pressedKeys[Keys.BUTTON_CIRCLE] = false;
}
} else {
if (pressedKeys[e.getKeyCode()]) {
pressedKeyCount--;
pressedKeys[e.getKeyCode()] = false;
}
}
}
app.getGraphics().requestRendering();
}
return isCatchKey(keyCode);
}
@Override
public void setOnscreenKeyboardVisible (final boolean visible) {
setOnscreenKeyboardVisible(visible, OnscreenKeyboardType.Default);
}
@Override
public void setOnscreenKeyboardVisible (final boolean visible, final OnscreenKeyboardType type) {
handle.post(new Runnable() {
public void run () {
InputMethodManager manager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (visible) {
View view = ((AndroidGraphics)app.getGraphics()).getView();
OnscreenKeyboardType tmp = type == null ? OnscreenKeyboardType.Default : type;
if (((GLSurfaceView20)view).onscreenKeyboardType != tmp) {
((GLSurfaceView20)view).onscreenKeyboardType = tmp;
manager.restartInput(view);
}
view.setFocusable(true);
view.setFocusableInTouchMode(true);
manager.showSoftInput(((AndroidGraphics)app.getGraphics()).getView(), 0);
} else {
manager.hideSoftInputFromWindow(((AndroidGraphics)app.getGraphics()).getView().getWindowToken(), 0);
}
}
});
}
@Override
public void vibrate (int milliseconds) {
haptics.vibrate(milliseconds);
}
@Override
public void vibrate (int milliseconds, boolean fallback) {
haptics.vibrate(milliseconds);
}
@Override
public void vibrate (int milliseconds, int amplitude, boolean fallback) {
haptics.vibrate(milliseconds, amplitude, fallback);
}
@Override
public void vibrate (VibrationType vibrationType) {
haptics.vibrate(vibrationType);
}
@Override
public boolean justTouched () {
return justTouched;
}
@Override
public boolean isButtonPressed (int button) {
synchronized (this) {
if (hasMultitouch) {
for (int pointer = 0; pointer < NUM_TOUCHES; pointer++) {
if (touched[pointer] && (this.button[pointer] == button)) {
return true;
}
}
}
return (touched[0] && (this.button[0] == button));
}
}
@Override
public boolean isButtonJustPressed (int button) {
if (button < 0 || button > NUM_TOUCHES) return false;
return justPressedButtons[button];
}
final float[] R = new float[9];
final float[] orientation = new float[3];
private void updateOrientation () {
if (rotationVectorAvailable) {
SensorManager.getRotationMatrixFromVector(R, rotationVectorValues);
} else if (!SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticFieldValues)) {
return; // compass + accelerometer in free fall
}
SensorManager.getOrientation(R, orientation);
azimuth = (float)Math.toDegrees(orientation[0]);
pitch = (float)Math.toDegrees(orientation[1]);
roll = (float)Math.toDegrees(orientation[2]);
}
/** Returns the rotation matrix describing the devices rotation as per
* <a href= "http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[],
* float[], float[])" >SensorManager#getRotationMatrix(float[], float[], float[], float[])</a>. Does not manipulate the matrix
* if the platform does not have an accelerometer and compass, or a rotation vector sensor.
* @param matrix */
public void getRotationMatrix (float[] matrix) {
if (rotationVectorAvailable)
SensorManager.getRotationMatrixFromVector(matrix, rotationVectorValues);
else // compass + accelerometer
SensorManager.getRotationMatrix(matrix, null, accelerometerValues, magneticFieldValues);
}
@Override
public float getAzimuth () {
if (!compassAvailable && !rotationVectorAvailable) return 0;
updateOrientation();
return azimuth;
}
@Override
public float getPitch () {
if (!compassAvailable && !rotationVectorAvailable) return 0;
updateOrientation();
return pitch;
}
@Override
public float getRoll () {
if (!compassAvailable && !rotationVectorAvailable) return 0;
updateOrientation();
return roll;
}
void registerSensorListeners () {
if (config.useAccelerometer) {
manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).isEmpty()) {
accelerometerAvailable = false;
} else {
Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
accelerometerListener = new SensorListener();
accelerometerAvailable = manager.registerListener(accelerometerListener, accelerometer, config.sensorDelay);
}
} else
accelerometerAvailable = false;
if (config.useGyroscope) {
manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
if (manager.getSensorList(Sensor.TYPE_GYROSCOPE).isEmpty()) {
gyroscopeAvailable = false;
} else {
Sensor gyroscope = manager.getSensorList(Sensor.TYPE_GYROSCOPE).get(0);
gyroscopeListener = new SensorListener();
gyroscopeAvailable = manager.registerListener(gyroscopeListener, gyroscope, config.sensorDelay);
}
} else
gyroscopeAvailable = false;
rotationVectorAvailable = false;
if (config.useRotationVectorSensor) {
if (manager == null) manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
List<Sensor> rotationVectorSensors = manager.getSensorList(Sensor.TYPE_ROTATION_VECTOR);
if (!rotationVectorSensors.isEmpty()) {
rotationVectorListener = new SensorListener();
for (Sensor sensor : rotationVectorSensors) { // favor AOSP sensor
if (sensor.getVendor().equals("Google Inc.") && sensor.getVersion() == 3) {
rotationVectorAvailable = manager.registerListener(rotationVectorListener, sensor, config.sensorDelay);
break;
}
}
if (!rotationVectorAvailable) rotationVectorAvailable = manager.registerListener(rotationVectorListener,
rotationVectorSensors.get(0), config.sensorDelay);
}
}
if (config.useCompass && !rotationVectorAvailable) {
if (manager == null) manager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = manager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
if (sensor != null) {
compassAvailable = accelerometerAvailable;
if (compassAvailable) {
compassListener = new SensorListener();
compassAvailable = manager.registerListener(compassListener, sensor, config.sensorDelay);
}
} else {
compassAvailable = false;
}
} else
compassAvailable = false;
Gdx.app.log("AndroidInput", "sensor listener setup");
}
void unregisterSensorListeners () {
if (manager != null) {
if (accelerometerListener != null) {
manager.unregisterListener(accelerometerListener);
accelerometerListener = null;
}
if (gyroscopeListener != null) {
manager.unregisterListener(gyroscopeListener);
gyroscopeListener = null;
}
if (rotationVectorListener != null) {
manager.unregisterListener(rotationVectorListener);
rotationVectorListener = null;
}
if (compassListener != null) {
manager.unregisterListener(compassListener);
compassListener = null;
}
manager = null;
}
Gdx.app.log("AndroidInput", "sensor listener tear down");
}
@Override
public InputProcessor getInputProcessor () {
return this.processor;
}
@Override
public boolean isPeripheralAvailable (Peripheral peripheral) {
if (peripheral == Peripheral.Accelerometer) return accelerometerAvailable;
if (peripheral == Peripheral.Gyroscope) return gyroscopeAvailable;
if (peripheral == Peripheral.Compass) return compassAvailable;
if (peripheral == Peripheral.HardwareKeyboard) return keyboardAvailable;
if (peripheral == Peripheral.OnscreenKeyboard) return true;
if (peripheral == Peripheral.Vibrator) return haptics.hasVibratorAvailable();
if (peripheral == Peripheral.HapticFeedback) return haptics.hasHapticsSupport();
if (peripheral == Peripheral.MultitouchScreen) return hasMultitouch;
if (peripheral == Peripheral.RotationVector) return rotationVectorAvailable;
if (peripheral == Peripheral.Pressure) return true;
return false;
}
public int getFreePointerIndex () {
int len = realId.length;
for (int i = 0; i < len; i++) {
if (realId[i] == -1) return i;
}
pressure = resize(pressure);
realId = resize(realId);
touchX = resize(touchX);
touchY = resize(touchY);
deltaX = resize(deltaX);
deltaY = resize(deltaY);
touched = resize(touched);
button = resize(button);
return len;
}
private int[] resize (int[] orig) {
int[] tmp = new int[orig.length + 2];
System.arraycopy(orig, 0, tmp, 0, orig.length);
return tmp;
}
private boolean[] resize (boolean[] orig) {
boolean[] tmp = new boolean[orig.length + 2];
System.arraycopy(orig, 0, tmp, 0, orig.length);
return tmp;
}
private float[] resize (float[] orig) {
float[] tmp = new float[orig.length + 2];
System.arraycopy(orig, 0, tmp, 0, orig.length);
return tmp;
}
public int lookUpPointerIndex (int pointerId) {
int len = realId.length;
for (int i = 0; i < len; i++) {
if (realId[i] == pointerId) return i;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
sb.append(i + ":" + realId[i] + " ");
}
Gdx.app.log("AndroidInput", "Pointer ID lookup failed: " + pointerId + ", " + sb.toString());
return -1;
}
@Override
public int getRotation () {
int orientation = 0;
if (context instanceof Activity) {
orientation = ((Activity)context).getWindowManager().getDefaultDisplay().getRotation();
} else {
orientation = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
}
switch (orientation) {
case Surface.ROTATION_0:
return 0;
case Surface.ROTATION_90:
return 90;
case Surface.ROTATION_180:
return 180;
case Surface.ROTATION_270:
return 270;
default:
return 0;
}
}
@Override
public Orientation getNativeOrientation () {
return nativeOrientation;
}
@Override
public void setCursorCatched (boolean catched) {
}
@Override
public boolean isCursorCatched () {
return false;
}
@Override
public int getDeltaX () {
return deltaX[0];
}
@Override
public int getDeltaX (int pointer) {
return deltaX[pointer];
}
@Override
public int getDeltaY () {
return deltaY[0];
}
@Override
public int getDeltaY (int pointer) {
return deltaY[pointer];
}
@Override
public void setCursorPosition (int x, int y) {
}
@Override
public long getCurrentEventTime () {
return currentEventTimeStamp;
}
@Override
public void addKeyListener (OnKeyListener listener) {
keyListeners.add(listener);
}
@Override
public boolean onGenericMotion (View view, MotionEvent event) {
if (mouseHandler.onGenericMotion(event, this)) return true;
for (int i = 0, n = genericMotionListeners.size(); i < n; i++)
if (genericMotionListeners.get(i).onGenericMotion(view, event)) return true;
return false;
}
@Override
public void addGenericMotionListener (OnGenericMotionListener listener) {
genericMotionListeners.add(listener);
}
@Override
public void onPause () {
unregisterSensorListeners();
}
@Override
public void onResume () {
registerSensorListeners();
}
@Override
public void onDreamingStarted () {
registerSensorListeners();
}
@Override
public void onDreamingStopped () {
unregisterSensorListeners();
}
/** Our implementation of SensorEventListener. Because Android doesn't like it when we register more than one Sensor to a
* single SensorEventListener, we add one of these for each Sensor. Could use an anonymous class, but I don't see any harm in
* explicitly defining it here. Correct me if I am wrong. */
private class SensorListener implements SensorEventListener {
public SensorListener () {
}
@Override
public void onAccuracyChanged (Sensor arg0, int arg1) {
}
@Override
public void onSensorChanged (SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
if (nativeOrientation == Orientation.Portrait) {
System.arraycopy(event.values, 0, accelerometerValues, 0, accelerometerValues.length);
} else {
accelerometerValues[0] = event.values[1];
accelerometerValues[1] = -event.values[0];
accelerometerValues[2] = event.values[2];
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
System.arraycopy(event.values, 0, magneticFieldValues, 0, magneticFieldValues.length);
}
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
if (nativeOrientation == Orientation.Portrait) {
System.arraycopy(event.values, 0, gyroscopeValues, 0, gyroscopeValues.length);
} else {
gyroscopeValues[0] = event.values[1];
gyroscopeValues[1] = -event.values[0];
gyroscopeValues[2] = event.values[2];
}
}
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
if (nativeOrientation == Orientation.Portrait) {
System.arraycopy(event.values, 0, rotationVectorValues, 0, rotationVectorValues.length);
} else {
rotationVectorValues[0] = event.values[1];
rotationVectorValues[1] = -event.values[0];
rotationVectorValues[2] = event.values[2];
}
}
}
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d-gwt/build.gradle | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
dependencies {
api libraries.gwt
compileOnly libraries.compileOnly.gwt
}
configurations.all {
// gwt-dev pulls in apache-jsp (Tomcat), but we don't need it and it messes with gretty
exclude group: 'org.eclipse.jetty', module: 'apache-jsp'
}
sourceSets.main.java.exclude "**/System.java"
eclipse {
classpath {
containers += [
'com.google.gwt.eclipse.core.GWT_CONTAINER',
'com.gwtplugins.gwt.eclipse.core.GWT_CONTAINER'
]
file {
withXml {
def node = it.asNode()
// Collect nodes to modify
def nodesToModify = []
node.children().each { c ->
if (c.attribute('path').equals('src')) {
nodesToModify << c
}
}
// Modify the collected nodes
nodesToModify.each { c ->
def newAttrs = c.attributes().collectEntries { [(it.key): it.value] }
newAttrs.put('excluding', 'com/badlogic/gdx/physics/box2d/gwt/emu/')
def newNode = new Node(c.parent(), c.name(), newAttrs)
c.children().each { child ->
newNode.append(child)
}
c.replaceNode(newNode)
}
// Add second classpath entry for emu folder if not exists
def emuNodes = node.children().findAll { it.name() == 'classpathentry' && it.'@path'.equals('src/com/badlogic/gdx/physics/box2d/gwt/emu/')}
if (emuNodes.size() == 0) {
node.appendNode('classpathentry', [
kind: 'src',
path: 'src/com/badlogic/gdx/physics/box2d/gwt/emu/',
excluding: 'java/lang/System.java'
])
}
}
}
}
} | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
dependencies {
api libraries.gwt
compileOnly libraries.compileOnly.gwt
}
configurations.all {
// gwt-dev pulls in apache-jsp (Tomcat), but we don't need it and it messes with gretty
exclude group: 'org.eclipse.jetty', module: 'apache-jsp'
}
sourceSets.main.java.exclude "**/System.java"
eclipse {
classpath {
containers += [
'com.google.gwt.eclipse.core.GWT_CONTAINER',
'com.gwtplugins.gwt.eclipse.core.GWT_CONTAINER'
]
file {
withXml {
def node = it.asNode()
// Collect nodes to modify
def nodesToModify = []
node.children().each { c ->
if (c.attribute('path').equals('src')) {
nodesToModify << c
}
}
// Modify the collected nodes
nodesToModify.each { c ->
def newAttrs = c.attributes().collectEntries { [(it.key): it.value] }
newAttrs.put('excluding', 'com/badlogic/gdx/physics/box2d/gwt/emu/')
def newNode = new Node(c.parent(), c.name(), newAttrs)
c.children().each { child ->
newNode.append(child)
}
c.replaceNode(newNode)
}
// Add second classpath entry for emu folder if not exists
def emuNodes = node.children().findAll { it.name() == 'classpathentry' && it.'@path'.equals('src/com/badlogic/gdx/physics/box2d/gwt/emu/')}
if (emuNodes.size() == 0) {
node.appendNode('classpathentry', [
kind: 'src',
path: 'src/com/badlogic/gdx/physics/box2d/gwt/emu/',
excluding: 'java/lang/System.java'
])
}
}
}
}
} | -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./gdx/src/com/badlogic/gdx/graphics/g3d/utils/AnimationController.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.utils;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.model.Animation;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Pool;
/** Class to control one or more {@link Animation}s on a {@link ModelInstance}. Use the
* {@link #setAnimation(String, int, float, AnimationListener)} method to change the current animation. Use the
* {@link #animate(String, int, float, AnimationListener, float)} method to start an animation, optionally blending onto the
* current animation. Use the {@link #queue(String, int, float, AnimationListener, float)} method to queue an animation to be
* played when the current animation is finished. Use the {@link #action(String, int, float, AnimationListener, float)} method to
* play a (short) animation on top of the current animation.
*
* You can use multiple AnimationControllers on the same ModelInstance, as long as they don't interfere with each other (don't
* affect the same {@link Node}s).
*
* @author Xoppa */
public class AnimationController extends BaseAnimationController {
/** Listener that will be informed when an animation is looped or completed.
* @author Xoppa */
public interface AnimationListener {
/** Gets called when an animation is completed.
* @param animation The animation which just completed. */
void onEnd (final AnimationDesc animation);
/** Gets called when an animation is looped. The {@link AnimationDesc#loopCount} is updated prior to this call and can be
* read or written to alter the number of remaining loops.
* @param animation The animation which just looped. */
void onLoop (final AnimationDesc animation);
}
/** Class describing how to play and {@link Animation}. You can read the values within this class to get the progress of the
* animation. Do not change the values. Only valid when the animation is currently played.
* @author Xoppa */
public static class AnimationDesc {
/** Listener which will be informed when the animation is looped or ended. */
public AnimationListener listener;
/** The animation to be applied. */
public Animation animation;
/** The speed at which to play the animation (can be negative), 1.0 for normal speed. */
public float speed;
/** The current animation time. */
public float time;
/** The offset within the animation (animation time = offsetTime + time) */
public float offset;
/** The duration of the animation */
public float duration;
/** The number of remaining loops, negative for continuous, zero if stopped. */
public int loopCount;
protected AnimationDesc () {
}
/** @param delta delta time, must be positive.
* @return the remaining time or -1 if still animating. */
protected float update (float delta) {
if (loopCount != 0 && animation != null) {
int loops;
final float diff = speed * delta;
if (!MathUtils.isZero(duration)) {
time += diff;
if (speed < 0) {
float invTime = duration - time;
loops = (int)Math.abs(invTime / duration);
invTime = Math.abs(invTime % duration);
time = duration - invTime;
} else {
loops = (int)Math.abs(time / duration);
time = Math.abs(time % duration);
}
} else
loops = 1;
for (int i = 0; i < loops; i++) {
if (loopCount > 0) loopCount--;
if (loopCount != 0 && listener != null) listener.onLoop(this);
if (loopCount == 0) {
final float result = ((loops - 1) - i) * duration + (diff < 0f ? duration - time : time);
time = (diff < 0f) ? 0f : duration;
if (listener != null) listener.onEnd(this);
return result;
}
}
return -1;
} else
return delta;
}
}
protected final Pool<AnimationDesc> animationPool = new Pool<AnimationDesc>() {
@Override
protected AnimationDesc newObject () {
return new AnimationDesc();
}
};
/** The animation currently playing. Do not alter this value. */
public AnimationDesc current;
/** The animation queued to be played when the {@link #current} animation is completed. Do not alter this value. */
public AnimationDesc queued;
/** The transition time which should be applied to the queued animation. Do not alter this value. */
public float queuedTransitionTime;
/** The animation which previously played. Do not alter this value. */
public AnimationDesc previous;
/** The current transition time. Do not alter this value. */
public float transitionCurrentTime;
/** The target transition time. Do not alter this value. */
public float transitionTargetTime;
/** Whether an action is being performed. Do not alter this value. */
public boolean inAction;
/** When true a call to {@link #update(float)} will not be processed. */
public boolean paused;
/** Whether to allow the same animation to be played while playing that animation. */
public boolean allowSameAnimation;
private boolean justChangedAnimation = false;
/** Construct a new AnimationController.
* @param target The {@link ModelInstance} on which the animations will be performed. */
public AnimationController (final ModelInstance target) {
super(target);
}
private AnimationDesc obtain (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
if (anim == null) return null;
final AnimationDesc result = animationPool.obtain();
result.animation = anim;
result.listener = listener;
result.loopCount = loopCount;
result.speed = speed;
result.offset = offset;
result.duration = duration < 0 ? (anim.duration - offset) : duration;
result.time = speed < 0 ? result.duration : 0.f;
return result;
}
private AnimationDesc obtain (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
if (id == null) return null;
final Animation anim = target.getAnimation(id);
if (anim == null) throw new GdxRuntimeException("Unknown animation: " + id);
return obtain(anim, offset, duration, loopCount, speed, listener);
}
private AnimationDesc obtain (final AnimationDesc anim) {
return obtain(anim.animation, anim.offset, anim.duration, anim.loopCount, anim.speed, anim.listener);
}
/** Update any animations currently being played.
* @param delta The time elapsed since last update, change this to alter the overall speed (can be negative). */
public void update (float delta) {
if (paused) return;
if (previous != null && ((transitionCurrentTime += delta) >= transitionTargetTime)) {
removeAnimation(previous.animation);
justChangedAnimation = true;
animationPool.free(previous);
previous = null;
}
if (justChangedAnimation) {
target.calculateTransforms();
justChangedAnimation = false;
}
if (current == null || current.loopCount == 0 || current.animation == null) return;
final float remain = current.update(delta);
if (remain >= 0f && queued != null) {
inAction = false;
animate(queued, queuedTransitionTime);
queued = null;
if (remain > 0f) update(remain);
return;
}
if (previous != null)
applyAnimations(previous.animation, previous.offset + previous.time, current.animation, current.offset + current.time,
transitionCurrentTime / transitionTargetTime);
else
applyAnimation(current.animation, current.offset + current.time);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id) {
return setAnimation(id, 1, 1.0f, null);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to loop the animation, zero to play the animation only once, negative to continuously
* loop the animation.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount) {
return setAnimation(id, loopCount, 1.0f, null);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, final AnimationListener listener) {
return setAnimation(id, 1, 1.0f, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount, final AnimationListener listener) {
return setAnimation(id, loopCount, 1.0f, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount, float speed, final AnimationListener listener) {
return setAnimation(id, 0f, -1f, loopCount, speed, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
return setAnimation(obtain(id, offset, duration, loopCount, speed, listener));
}
/** Set the active animation, replacing any current animation. */
protected AnimationDesc setAnimation (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
return setAnimation(obtain(anim, offset, duration, loopCount, speed, listener));
}
/** Set the active animation, replacing any current animation. */
protected AnimationDesc setAnimation (final AnimationDesc anim) {
if (current == null)
current = anim;
else {
if (!allowSameAnimation && anim != null && current.animation == anim.animation)
anim.time = current.time;
else
removeAnimation(current.animation);
animationPool.free(current);
current = anim;
}
justChangedAnimation = true;
return anim;
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, float transitionTime) {
return animate(id, 1, 1.0f, null, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, final AnimationListener listener, float transitionTime) {
return animate(id, 1, 1.0f, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to loop the animation, zero to play the animation only once, negative to continuously
* loop the animation.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, int loopCount, final AnimationListener listener, float transitionTime) {
return animate(id, loopCount, 1.0f, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return animate(id, 0f, -1f, loopCount, speed, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return animate(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time. */
protected AnimationDesc animate (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return animate(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time. */
protected AnimationDesc animate (final AnimationDesc anim, float transitionTime) {
if (current == null || current.loopCount == 0)
current = anim;
else if (inAction)
queue(anim, transitionTime);
else if (!allowSameAnimation && anim != null && current.animation == anim.animation) {
anim.time = current.time;
animationPool.free(current);
current = anim;
} else {
if (previous != null) {
removeAnimation(previous.animation);
animationPool.free(previous);
}
previous = current;
current = anim;
transitionCurrentTime = 0f;
transitionTargetTime = transitionTime;
}
return anim;
}
/** Queue an animation to be applied when the {@link #current} animation is finished. If the current animation is continuously
* looping it will be synchronized on next loop.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc queue (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return queue(id, 0f, -1f, loopCount, speed, listener, transitionTime);
}
/** Queue an animation to be applied when the {@link #current} animation is finished. If the current animation is continuously
* looping it will be synchronized on next loop.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc queue (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return queue(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Queue an animation to be applied when the current is finished. If current is continuous it will be synced on next loop. */
protected AnimationDesc queue (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return queue(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Queue an animation to be applied when the current is finished. If current is continuous it will be synced on next loop. */
protected AnimationDesc queue (final AnimationDesc anim, float transitionTime) {
if (current == null || current.loopCount == 0)
animate(anim, transitionTime);
else {
if (queued != null) animationPool.free(queued);
queued = anim;
queuedTransitionTime = transitionTime;
if (current.loopCount < 0) current.loopCount = 1;
}
return anim;
}
/** Apply an action animation on top of the current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc action (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return action(id, 0, -1f, loopCount, speed, listener, transitionTime);
}
/** Apply an action animation on top of the current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc action (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return action(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Apply an action animation on top of the current animation. */
protected AnimationDesc action (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return action(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Apply an action animation on top of the current animation. */
protected AnimationDesc action (final AnimationDesc anim, float transitionTime) {
if (anim.loopCount < 0) throw new GdxRuntimeException("An action cannot be continuous");
if (current == null || current.loopCount == 0)
animate(anim, transitionTime);
else {
AnimationDesc toQueue = inAction ? null : obtain(current);
inAction = false;
animate(anim, transitionTime);
inAction = true;
if (toQueue != null) queue(toQueue, transitionTime);
}
return anim;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.utils;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.model.Animation;
import com.badlogic.gdx.graphics.g3d.model.Node;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Pool;
/** Class to control one or more {@link Animation}s on a {@link ModelInstance}. Use the
* {@link #setAnimation(String, int, float, AnimationListener)} method to change the current animation. Use the
* {@link #animate(String, int, float, AnimationListener, float)} method to start an animation, optionally blending onto the
* current animation. Use the {@link #queue(String, int, float, AnimationListener, float)} method to queue an animation to be
* played when the current animation is finished. Use the {@link #action(String, int, float, AnimationListener, float)} method to
* play a (short) animation on top of the current animation.
*
* You can use multiple AnimationControllers on the same ModelInstance, as long as they don't interfere with each other (don't
* affect the same {@link Node}s).
*
* @author Xoppa */
public class AnimationController extends BaseAnimationController {
/** Listener that will be informed when an animation is looped or completed.
* @author Xoppa */
public interface AnimationListener {
/** Gets called when an animation is completed.
* @param animation The animation which just completed. */
void onEnd (final AnimationDesc animation);
/** Gets called when an animation is looped. The {@link AnimationDesc#loopCount} is updated prior to this call and can be
* read or written to alter the number of remaining loops.
* @param animation The animation which just looped. */
void onLoop (final AnimationDesc animation);
}
/** Class describing how to play and {@link Animation}. You can read the values within this class to get the progress of the
* animation. Do not change the values. Only valid when the animation is currently played.
* @author Xoppa */
public static class AnimationDesc {
/** Listener which will be informed when the animation is looped or ended. */
public AnimationListener listener;
/** The animation to be applied. */
public Animation animation;
/** The speed at which to play the animation (can be negative), 1.0 for normal speed. */
public float speed;
/** The current animation time. */
public float time;
/** The offset within the animation (animation time = offsetTime + time) */
public float offset;
/** The duration of the animation */
public float duration;
/** The number of remaining loops, negative for continuous, zero if stopped. */
public int loopCount;
protected AnimationDesc () {
}
/** @param delta delta time, must be positive.
* @return the remaining time or -1 if still animating. */
protected float update (float delta) {
if (loopCount != 0 && animation != null) {
int loops;
final float diff = speed * delta;
if (!MathUtils.isZero(duration)) {
time += diff;
if (speed < 0) {
float invTime = duration - time;
loops = (int)Math.abs(invTime / duration);
invTime = Math.abs(invTime % duration);
time = duration - invTime;
} else {
loops = (int)Math.abs(time / duration);
time = Math.abs(time % duration);
}
} else
loops = 1;
for (int i = 0; i < loops; i++) {
if (loopCount > 0) loopCount--;
if (loopCount != 0 && listener != null) listener.onLoop(this);
if (loopCount == 0) {
final float result = ((loops - 1) - i) * duration + (diff < 0f ? duration - time : time);
time = (diff < 0f) ? 0f : duration;
if (listener != null) listener.onEnd(this);
return result;
}
}
return -1;
} else
return delta;
}
}
protected final Pool<AnimationDesc> animationPool = new Pool<AnimationDesc>() {
@Override
protected AnimationDesc newObject () {
return new AnimationDesc();
}
};
/** The animation currently playing. Do not alter this value. */
public AnimationDesc current;
/** The animation queued to be played when the {@link #current} animation is completed. Do not alter this value. */
public AnimationDesc queued;
/** The transition time which should be applied to the queued animation. Do not alter this value. */
public float queuedTransitionTime;
/** The animation which previously played. Do not alter this value. */
public AnimationDesc previous;
/** The current transition time. Do not alter this value. */
public float transitionCurrentTime;
/** The target transition time. Do not alter this value. */
public float transitionTargetTime;
/** Whether an action is being performed. Do not alter this value. */
public boolean inAction;
/** When true a call to {@link #update(float)} will not be processed. */
public boolean paused;
/** Whether to allow the same animation to be played while playing that animation. */
public boolean allowSameAnimation;
private boolean justChangedAnimation = false;
/** Construct a new AnimationController.
* @param target The {@link ModelInstance} on which the animations will be performed. */
public AnimationController (final ModelInstance target) {
super(target);
}
private AnimationDesc obtain (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
if (anim == null) return null;
final AnimationDesc result = animationPool.obtain();
result.animation = anim;
result.listener = listener;
result.loopCount = loopCount;
result.speed = speed;
result.offset = offset;
result.duration = duration < 0 ? (anim.duration - offset) : duration;
result.time = speed < 0 ? result.duration : 0.f;
return result;
}
private AnimationDesc obtain (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
if (id == null) return null;
final Animation anim = target.getAnimation(id);
if (anim == null) throw new GdxRuntimeException("Unknown animation: " + id);
return obtain(anim, offset, duration, loopCount, speed, listener);
}
private AnimationDesc obtain (final AnimationDesc anim) {
return obtain(anim.animation, anim.offset, anim.duration, anim.loopCount, anim.speed, anim.listener);
}
/** Update any animations currently being played.
* @param delta The time elapsed since last update, change this to alter the overall speed (can be negative). */
public void update (float delta) {
if (paused) return;
if (previous != null && ((transitionCurrentTime += delta) >= transitionTargetTime)) {
removeAnimation(previous.animation);
justChangedAnimation = true;
animationPool.free(previous);
previous = null;
}
if (justChangedAnimation) {
target.calculateTransforms();
justChangedAnimation = false;
}
if (current == null || current.loopCount == 0 || current.animation == null) return;
final float remain = current.update(delta);
if (remain >= 0f && queued != null) {
inAction = false;
animate(queued, queuedTransitionTime);
queued = null;
if (remain > 0f) update(remain);
return;
}
if (previous != null)
applyAnimations(previous.animation, previous.offset + previous.time, current.animation, current.offset + current.time,
transitionCurrentTime / transitionTargetTime);
else
applyAnimation(current.animation, current.offset + current.time);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id) {
return setAnimation(id, 1, 1.0f, null);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to loop the animation, zero to play the animation only once, negative to continuously
* loop the animation.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount) {
return setAnimation(id, loopCount, 1.0f, null);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, final AnimationListener listener) {
return setAnimation(id, 1, 1.0f, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount, final AnimationListener listener) {
return setAnimation(id, loopCount, 1.0f, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, int loopCount, float speed, final AnimationListener listener) {
return setAnimation(id, 0f, -1f, loopCount, speed, listener);
}
/** Set the active animation, replacing any current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc setAnimation (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
return setAnimation(obtain(id, offset, duration, loopCount, speed, listener));
}
/** Set the active animation, replacing any current animation. */
protected AnimationDesc setAnimation (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener) {
return setAnimation(obtain(anim, offset, duration, loopCount, speed, listener));
}
/** Set the active animation, replacing any current animation. */
protected AnimationDesc setAnimation (final AnimationDesc anim) {
if (current == null)
current = anim;
else {
if (!allowSameAnimation && anim != null && current.animation == anim.animation)
anim.time = current.time;
else
removeAnimation(current.animation);
animationPool.free(current);
current = anim;
}
justChangedAnimation = true;
return anim;
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, float transitionTime) {
return animate(id, 1, 1.0f, null, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, final AnimationListener listener, float transitionTime) {
return animate(id, 1, 1.0f, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to loop the animation, zero to play the animation only once, negative to continuously
* loop the animation.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, int loopCount, final AnimationListener listener, float transitionTime) {
return animate(id, loopCount, 1.0f, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return animate(id, 0f, -1f, loopCount, speed, listener, transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc animate (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return animate(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time. */
protected AnimationDesc animate (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return animate(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Changes the current animation by blending the new on top of the old during the transition time. */
protected AnimationDesc animate (final AnimationDesc anim, float transitionTime) {
if (current == null || current.loopCount == 0)
current = anim;
else if (inAction)
queue(anim, transitionTime);
else if (!allowSameAnimation && anim != null && current.animation == anim.animation) {
anim.time = current.time;
animationPool.free(current);
current = anim;
} else {
if (previous != null) {
removeAnimation(previous.animation);
animationPool.free(previous);
}
previous = current;
current = anim;
transitionCurrentTime = 0f;
transitionTargetTime = transitionTime;
}
return anim;
}
/** Queue an animation to be applied when the {@link #current} animation is finished. If the current animation is continuously
* looping it will be synchronized on next loop.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc queue (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return queue(id, 0f, -1f, loopCount, speed, listener, transitionTime);
}
/** Queue an animation to be applied when the {@link #current} animation is finished. If the current animation is continuously
* looping it will be synchronized on next loop.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc queue (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return queue(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Queue an animation to be applied when the current is finished. If current is continuous it will be synced on next loop. */
protected AnimationDesc queue (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return queue(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Queue an animation to be applied when the current is finished. If current is continuous it will be synced on next loop. */
protected AnimationDesc queue (final AnimationDesc anim, float transitionTime) {
if (current == null || current.loopCount == 0)
animate(anim, transitionTime);
else {
if (queued != null) animationPool.free(queued);
queued = anim;
queuedTransitionTime = transitionTime;
if (current.loopCount < 0) current.loopCount = 1;
}
return anim;
}
/** Apply an action animation on top of the current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc action (final String id, int loopCount, float speed, final AnimationListener listener,
float transitionTime) {
return action(id, 0, -1f, loopCount, speed, listener, transitionTime);
}
/** Apply an action animation on top of the current animation.
* @param id The ID of the {@link Animation} within the {@link ModelInstance}.
* @param offset The offset in seconds to the start of the animation.
* @param duration The duration in seconds of the animation (or negative to play till the end of the animation).
* @param loopCount The number of times to play the animation, 1 to play the animation only once, negative to continuously loop
* the animation.
* @param speed The speed at which the animation should be played. Default is 1.0f. A value of 2.0f will play the animation at
* twice the normal speed, a value of 0.5f will play the animation at half the normal speed, etc. This value can be
* negative, causing the animation to played in reverse. This value cannot be zero.
* @param listener The {@link AnimationListener} which will be informed when the animation is looped or completed.
* @param transitionTime The time to transition the new animation on top of the currently playing animation (if any).
* @return The {@link AnimationDesc} which can be read to get the progress of the animation. Will be invalid when the animation
* is completed. */
public AnimationDesc action (final String id, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return action(obtain(id, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Apply an action animation on top of the current animation. */
protected AnimationDesc action (final Animation anim, float offset, float duration, int loopCount, float speed,
final AnimationListener listener, float transitionTime) {
return action(obtain(anim, offset, duration, loopCount, speed, listener), transitionTime);
}
/** Apply an action animation on top of the current animation. */
protected AnimationDesc action (final AnimationDesc anim, float transitionTime) {
if (anim.loopCount < 0) throw new GdxRuntimeException("An action cannot be continuous");
if (current == null || current.loopCount == 0)
animate(anim, transitionTime);
else {
AnimationDesc toQueue = inAction ? null : obtain(current);
inAction = false;
animate(anim, transitionTime);
inAction = true;
if (toQueue != null) queue(toQueue, transitionTime);
}
return anim;
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btOptimizedBvh.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btOptimizedBvh extends btQuantizedBvh {
private long swigCPtr;
protected btOptimizedBvh (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btOptimizedBvh_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btOptimizedBvh, normally you should not need this constructor it's intended for low-level usage. */
public btOptimizedBvh (long cPtr, boolean cMemoryOwn) {
this("btOptimizedBvh", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btOptimizedBvh_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btOptimizedBvh obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btOptimizedBvh(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btOptimizedBvh_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btOptimizedBvh_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btOptimizedBvh_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btOptimizedBvh_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btOptimizedBvh_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btOptimizedBvh_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btOptimizedBvh_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btOptimizedBvh_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btOptimizedBvh () {
this(CollisionJNI.new_btOptimizedBvh(), true);
}
public void build (btStridingMeshInterface triangles, boolean useQuantizedAabbCompression, Vector3 bvhAabbMin,
Vector3 bvhAabbMax) {
CollisionJNI.btOptimizedBvh_build(swigCPtr, this, btStridingMeshInterface.getCPtr(triangles), triangles,
useQuantizedAabbCompression, bvhAabbMin, bvhAabbMax);
}
public void refit (btStridingMeshInterface triangles, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btOptimizedBvh_refit(swigCPtr, this, btStridingMeshInterface.getCPtr(triangles), triangles, aabbMin, aabbMax);
}
public void refitPartial (btStridingMeshInterface triangles, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btOptimizedBvh_refitPartial(swigCPtr, this, btStridingMeshInterface.getCPtr(triangles), triangles, aabbMin,
aabbMax);
}
public void updateBvhNodes (btStridingMeshInterface meshInterface, int firstNode, int endNode, int index) {
CollisionJNI.btOptimizedBvh_updateBvhNodes(swigCPtr, this, btStridingMeshInterface.getCPtr(meshInterface), meshInterface,
firstNode, endNode, index);
}
public boolean serializeInPlace (long o_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) {
return CollisionJNI.btOptimizedBvh_serializeInPlace(swigCPtr, this, o_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
}
public static btOptimizedBvh deSerializeInPlace (long i_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) {
long cPtr = CollisionJNI.btOptimizedBvh_deSerializeInPlace(i_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
return (cPtr == 0) ? null : new btOptimizedBvh(cPtr, false);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btOptimizedBvh extends btQuantizedBvh {
private long swigCPtr;
protected btOptimizedBvh (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btOptimizedBvh_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btOptimizedBvh, normally you should not need this constructor it's intended for low-level usage. */
public btOptimizedBvh (long cPtr, boolean cMemoryOwn) {
this("btOptimizedBvh", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btOptimizedBvh_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btOptimizedBvh obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btOptimizedBvh(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btOptimizedBvh_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btOptimizedBvh_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btOptimizedBvh_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btOptimizedBvh_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btOptimizedBvh_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btOptimizedBvh_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btOptimizedBvh_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btOptimizedBvh_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btOptimizedBvh () {
this(CollisionJNI.new_btOptimizedBvh(), true);
}
public void build (btStridingMeshInterface triangles, boolean useQuantizedAabbCompression, Vector3 bvhAabbMin,
Vector3 bvhAabbMax) {
CollisionJNI.btOptimizedBvh_build(swigCPtr, this, btStridingMeshInterface.getCPtr(triangles), triangles,
useQuantizedAabbCompression, bvhAabbMin, bvhAabbMax);
}
public void refit (btStridingMeshInterface triangles, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btOptimizedBvh_refit(swigCPtr, this, btStridingMeshInterface.getCPtr(triangles), triangles, aabbMin, aabbMax);
}
public void refitPartial (btStridingMeshInterface triangles, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btOptimizedBvh_refitPartial(swigCPtr, this, btStridingMeshInterface.getCPtr(triangles), triangles, aabbMin,
aabbMax);
}
public void updateBvhNodes (btStridingMeshInterface meshInterface, int firstNode, int endNode, int index) {
CollisionJNI.btOptimizedBvh_updateBvhNodes(swigCPtr, this, btStridingMeshInterface.getCPtr(meshInterface), meshInterface,
firstNode, endNode, index);
}
public boolean serializeInPlace (long o_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) {
return CollisionJNI.btOptimizedBvh_serializeInPlace(swigCPtr, this, o_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
}
public static btOptimizedBvh deSerializeInPlace (long i_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) {
long cPtr = CollisionJNI.btOptimizedBvh_deSerializeInPlace(i_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
return (cPtr == 0) ? null : new btOptimizedBvh(cPtr, false);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btGimPairArray.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btGimPairArray extends BulletBase {
private long swigCPtr;
protected btGimPairArray (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btGimPairArray, normally you should not need this constructor it's intended for low-level usage. */
public btGimPairArray (long cPtr, boolean cMemoryOwn) {
this("btGimPairArray", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btGimPairArray obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btGimPairArray(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btGimPairArray operatorAssignment (btGimPairArray other) {
return new btGimPairArray(
CollisionJNI.btGimPairArray_operatorAssignment(swigCPtr, this, btGimPairArray.getCPtr(other), other), false);
}
public btGimPairArray () {
this(CollisionJNI.new_btGimPairArray__SWIG_0(), true);
}
public btGimPairArray (btGimPairArray otherArray) {
this(CollisionJNI.new_btGimPairArray__SWIG_1(btGimPairArray.getCPtr(otherArray), otherArray), true);
}
public int size () {
return CollisionJNI.btGimPairArray_size(swigCPtr, this);
}
public GIM_PAIR atConst (int n) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_atConst(swigCPtr, this, n), false);
}
public GIM_PAIR at (int n) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_at(swigCPtr, this, n), false);
}
public GIM_PAIR operatorSubscriptConst (int n) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_operatorSubscriptConst(swigCPtr, this, n), false);
}
public GIM_PAIR operatorSubscript (int n) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_operatorSubscript(swigCPtr, this, n), false);
}
public void clear () {
CollisionJNI.btGimPairArray_clear(swigCPtr, this);
}
public void pop_back () {
CollisionJNI.btGimPairArray_pop_back(swigCPtr, this);
}
public void resizeNoInitialize (int newsize) {
CollisionJNI.btGimPairArray_resizeNoInitialize(swigCPtr, this, newsize);
}
public void resize (int newsize, GIM_PAIR fillData) {
CollisionJNI.btGimPairArray_resize__SWIG_0(swigCPtr, this, newsize, GIM_PAIR.getCPtr(fillData), fillData);
}
public void resize (int newsize) {
CollisionJNI.btGimPairArray_resize__SWIG_1(swigCPtr, this, newsize);
}
public GIM_PAIR expandNonInitializing () {
return new GIM_PAIR(CollisionJNI.btGimPairArray_expandNonInitializing(swigCPtr, this), false);
}
public GIM_PAIR expand (GIM_PAIR fillValue) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_expand__SWIG_0(swigCPtr, this, GIM_PAIR.getCPtr(fillValue), fillValue),
false);
}
public GIM_PAIR expand () {
return new GIM_PAIR(CollisionJNI.btGimPairArray_expand__SWIG_1(swigCPtr, this), false);
}
public void push_back (GIM_PAIR _Val) {
CollisionJNI.btGimPairArray_push_back(swigCPtr, this, GIM_PAIR.getCPtr(_Val), _Val);
}
public int capacity () {
return CollisionJNI.btGimPairArray_capacity(swigCPtr, this);
}
public void reserve (int _Count) {
CollisionJNI.btGimPairArray_reserve(swigCPtr, this, _Count);
}
static public class less extends BulletBase {
private long swigCPtr;
protected less (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new less, normally you should not need this constructor it's intended for low-level usage. */
public less (long cPtr, boolean cMemoryOwn) {
this("less", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (less obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btGimPairArray_less(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public less () {
this(CollisionJNI.new_btGimPairArray_less(), true);
}
}
public void swap (int index0, int index1) {
CollisionJNI.btGimPairArray_swap(swigCPtr, this, index0, index1);
}
public void removeAtIndex (int index) {
CollisionJNI.btGimPairArray_removeAtIndex(swigCPtr, this, index);
}
public void initializeFromBuffer (long buffer, int size, int capacity) {
CollisionJNI.btGimPairArray_initializeFromBuffer(swigCPtr, this, buffer, size, capacity);
}
public void copyFromArray (btGimPairArray otherArray) {
CollisionJNI.btGimPairArray_copyFromArray(swigCPtr, this, btGimPairArray.getCPtr(otherArray), otherArray);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btGimPairArray extends BulletBase {
private long swigCPtr;
protected btGimPairArray (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btGimPairArray, normally you should not need this constructor it's intended for low-level usage. */
public btGimPairArray (long cPtr, boolean cMemoryOwn) {
this("btGimPairArray", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btGimPairArray obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btGimPairArray(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btGimPairArray operatorAssignment (btGimPairArray other) {
return new btGimPairArray(
CollisionJNI.btGimPairArray_operatorAssignment(swigCPtr, this, btGimPairArray.getCPtr(other), other), false);
}
public btGimPairArray () {
this(CollisionJNI.new_btGimPairArray__SWIG_0(), true);
}
public btGimPairArray (btGimPairArray otherArray) {
this(CollisionJNI.new_btGimPairArray__SWIG_1(btGimPairArray.getCPtr(otherArray), otherArray), true);
}
public int size () {
return CollisionJNI.btGimPairArray_size(swigCPtr, this);
}
public GIM_PAIR atConst (int n) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_atConst(swigCPtr, this, n), false);
}
public GIM_PAIR at (int n) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_at(swigCPtr, this, n), false);
}
public GIM_PAIR operatorSubscriptConst (int n) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_operatorSubscriptConst(swigCPtr, this, n), false);
}
public GIM_PAIR operatorSubscript (int n) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_operatorSubscript(swigCPtr, this, n), false);
}
public void clear () {
CollisionJNI.btGimPairArray_clear(swigCPtr, this);
}
public void pop_back () {
CollisionJNI.btGimPairArray_pop_back(swigCPtr, this);
}
public void resizeNoInitialize (int newsize) {
CollisionJNI.btGimPairArray_resizeNoInitialize(swigCPtr, this, newsize);
}
public void resize (int newsize, GIM_PAIR fillData) {
CollisionJNI.btGimPairArray_resize__SWIG_0(swigCPtr, this, newsize, GIM_PAIR.getCPtr(fillData), fillData);
}
public void resize (int newsize) {
CollisionJNI.btGimPairArray_resize__SWIG_1(swigCPtr, this, newsize);
}
public GIM_PAIR expandNonInitializing () {
return new GIM_PAIR(CollisionJNI.btGimPairArray_expandNonInitializing(swigCPtr, this), false);
}
public GIM_PAIR expand (GIM_PAIR fillValue) {
return new GIM_PAIR(CollisionJNI.btGimPairArray_expand__SWIG_0(swigCPtr, this, GIM_PAIR.getCPtr(fillValue), fillValue),
false);
}
public GIM_PAIR expand () {
return new GIM_PAIR(CollisionJNI.btGimPairArray_expand__SWIG_1(swigCPtr, this), false);
}
public void push_back (GIM_PAIR _Val) {
CollisionJNI.btGimPairArray_push_back(swigCPtr, this, GIM_PAIR.getCPtr(_Val), _Val);
}
public int capacity () {
return CollisionJNI.btGimPairArray_capacity(swigCPtr, this);
}
public void reserve (int _Count) {
CollisionJNI.btGimPairArray_reserve(swigCPtr, this, _Count);
}
static public class less extends BulletBase {
private long swigCPtr;
protected less (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new less, normally you should not need this constructor it's intended for low-level usage. */
public less (long cPtr, boolean cMemoryOwn) {
this("less", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (less obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btGimPairArray_less(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public less () {
this(CollisionJNI.new_btGimPairArray_less(), true);
}
}
public void swap (int index0, int index1) {
CollisionJNI.btGimPairArray_swap(swigCPtr, this, index0, index1);
}
public void removeAtIndex (int index) {
CollisionJNI.btGimPairArray_removeAtIndex(swigCPtr, this, index);
}
public void initializeFromBuffer (long buffer, int size, int capacity) {
CollisionJNI.btGimPairArray_initializeFromBuffer(swigCPtr, this, buffer, size, capacity);
}
public void copyFromArray (btGimPairArray otherArray) {
CollisionJNI.btGimPairArray_copyFromArray(swigCPtr, this, btGimPairArray.getCPtr(otherArray), otherArray);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/io/RandomAccessFile.java | /*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.io;
import java.nio.channels.FileChannel;
/** Saves binary data to the local storage; currently using hex encoding. The string is prefixed with "hex:"
* @author haustein */
public class RandomAccessFile /* implements DataOutput, DataInput, Closeable */ {
/*
* public final FileDescriptor getFD() throws IOException { }
*/
final String name;
final boolean writeable;
boolean dirty;
String data;
int newDataPos;
StringBuilder newData;
int pos;
int len;
DataInputStream dis = new DataInputStream(new RafInputStream());
DataOutputStream dos = new DataOutputStream(new RafOutputStream());
public RandomAccessFile (String name, String mode) throws FileNotFoundException {
this(new File(name), mode);
}
public RandomAccessFile (File file, String mode) throws FileNotFoundException {
name = file.getCanonicalPath();
mode = mode.toLowerCase();
if (!mode.equals("r") && !mode.equals("rw")) {
throw new IllegalArgumentException("mode: '" + mode + "'");
}
writeable = mode.equals("rw");
if (file.exists()) {
data = atob(File.LocalStorage.getItem(name));
len = data.length();
} else if (writeable) {
data = "";
dirty = true;
try {
flush();
} catch (IOException e) {
throw new FileNotFoundException("" + e);
}
} else {
throw new FileNotFoundException(name);
}
}
static native String btoa (String s) /*-{
return $wnd.btoa(s);
}-*/;
static native String atob (String s) /*-{
return $wnd.atob(s);
}-*/;
public int read () throws IOException {
return dis.read();
}
public int read (byte b[], int off, int len) throws IOException {
return dis.read(b, off, len);
}
public int read (byte b[]) throws IOException {
return dis.read(b);
}
public final void readFully (byte b[]) throws IOException {
dis.readFully(b);
}
public final void readFully (byte b[], int off, int len) throws IOException {
dis.readFully(b, off, len);
}
public int skipBytes (int n) throws IOException {
return dis.skipBytes(n);
}
public void write (int b) throws IOException {
dos.write(b);
};
public void write (byte b[]) throws IOException {
dos.write(b);
}
public void write (byte b[], int off, int len) throws IOException {
dos.write(b, off, len);
}
public long getFilePointer () throws IOException {
return pos;
}
public void seek (long pos) throws IOException {
if (pos < 0) {
throw new IllegalArgumentException();
}
this.pos = (int)pos;
}
public long length () throws IOException {
return len;
}
public void setLength (long newLength) throws IOException {
if (len != newLength) {
consolidate();
if (data.length() > newLength) {
data = data.substring(0, (int)newLength);
len = (int)newLength;
} else {
// System.out.println("padding " + (newLength - len) + " zeros in setLength to " + newLength);
while (len < newLength) {
write(0);
}
}
}
}
public void close () throws IOException {
if (data != null) {
flush();
data = null;
}
}
void consolidate () {
if (newData == null) {
return;
}
// System.out.println("consolidate(); ndp: " + newDataPos + " nd-len: " + newData.length());
if (data.length() < newDataPos) {
StringBuilder filler = new StringBuilder();
while (data.length() + filler.length() < newDataPos) {
filler.append('\0');
}
// System.out.println("padding " + (filler.length()) + " zeros in consolidate ");
data += filler.toString();
}
int p2 = newDataPos + newData.length();
data = data.substring(0, newDataPos) + newData.toString() + (p2 < data.length() ? data.substring(p2) : "");
newData = null;
}
void flush () throws IOException {
if (!dirty) {
return;
}
consolidate();
File.LocalStorage.setItem(name, btoa(data));
dirty = false;
}
public final boolean readBoolean () throws IOException {
return dis.readBoolean();
}
public final byte readByte () throws IOException {
return dis.readByte();
}
public final int readUnsignedByte () throws IOException {
return dis.readUnsignedByte();
}
public final short readShort () throws IOException {
return dis.readShort();
}
public final int readUnsignedShort () throws IOException {
return dis.readUnsignedShort();
}
public final char readChar () throws IOException {
return dis.readChar();
}
public final int readInt () throws IOException {
return dis.readInt();
}
public final long readLong () throws IOException {
return dis.readLong();
}
public final float readFloat () throws IOException {
return dis.readFloat();
}
public final double readDouble () throws IOException {
return dis.readDouble();
}
public final String readLine () throws IOException {
return dis.readLine();
}
public final String readUTF () throws IOException {
return dis.readUTF();
}
public final void writeBoolean (boolean v) throws IOException {
dos.writeBoolean(v);
}
public final void writeByte (int v) throws IOException {
dos.writeByte(v);
}
public final void writeShort (int v) throws IOException {
dos.writeShort(v);
}
public final void writeChar (int v) throws IOException {
dos.writeChar(v);
}
public final void writeInt (int v) throws IOException {
dos.writeInt(v);
}
public final void writeLong (long v) throws IOException {
dos.writeLong(v);
}
public final void writeFloat (float v) throws IOException {
dos.writeFloat(v);
}
public final void writeDouble (double v) throws IOException {
dos.writeDouble(v);
}
public final void writeBytes (String s) throws IOException {
dos.writeBytes(s);
}
public final void writeChars (String s) throws IOException {
dos.writeChars(s);
}
public final void writeUTF (String str) throws IOException {
dos.writeUTF(str);
}
public final FileChannel getChannel () throws IOException {
return null;
}
class RafInputStream extends InputStream {
@Override
public int read () throws IOException {
if (pos >= len) {
return -1;
} else {
consolidate();
return data.charAt(pos++);
// int p2 = (pos << 1);
// int result = Character.digit(data.charAt(p2), 16) * 16 +
// Character.digit(data.charAt(p2 + 1), 16);
// pos++;
// return result;
}
}
}
class RafOutputStream extends OutputStream {
public void write (int b) throws IOException {
if (!writeable) {
throw new IOException("not writeable");
}
if (newData == null) {
newDataPos = pos;
newData = new StringBuilder();
// System.out.println("no buf; newDataPos: " + pos);
} else if (newDataPos + newData.length() != pos) {
consolidate();
newDataPos = pos;
newData = new StringBuilder();
// System.out.println("pos mismatch; newDataPos: " + pos);
}
newData.append((char)(b & 255));
// newData.append("" + Character.forDigit((b >> 4) & 15, 16) +
// Character.forDigit(b & 15, 16));
pos++;
len = Math.max(pos, len);
dirty = true;
}
}
}
| /*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package java.io;
import java.nio.channels.FileChannel;
/** Saves binary data to the local storage; currently using hex encoding. The string is prefixed with "hex:"
* @author haustein */
public class RandomAccessFile /* implements DataOutput, DataInput, Closeable */ {
/*
* public final FileDescriptor getFD() throws IOException { }
*/
final String name;
final boolean writeable;
boolean dirty;
String data;
int newDataPos;
StringBuilder newData;
int pos;
int len;
DataInputStream dis = new DataInputStream(new RafInputStream());
DataOutputStream dos = new DataOutputStream(new RafOutputStream());
public RandomAccessFile (String name, String mode) throws FileNotFoundException {
this(new File(name), mode);
}
public RandomAccessFile (File file, String mode) throws FileNotFoundException {
name = file.getCanonicalPath();
mode = mode.toLowerCase();
if (!mode.equals("r") && !mode.equals("rw")) {
throw new IllegalArgumentException("mode: '" + mode + "'");
}
writeable = mode.equals("rw");
if (file.exists()) {
data = atob(File.LocalStorage.getItem(name));
len = data.length();
} else if (writeable) {
data = "";
dirty = true;
try {
flush();
} catch (IOException e) {
throw new FileNotFoundException("" + e);
}
} else {
throw new FileNotFoundException(name);
}
}
static native String btoa (String s) /*-{
return $wnd.btoa(s);
}-*/;
static native String atob (String s) /*-{
return $wnd.atob(s);
}-*/;
public int read () throws IOException {
return dis.read();
}
public int read (byte b[], int off, int len) throws IOException {
return dis.read(b, off, len);
}
public int read (byte b[]) throws IOException {
return dis.read(b);
}
public final void readFully (byte b[]) throws IOException {
dis.readFully(b);
}
public final void readFully (byte b[], int off, int len) throws IOException {
dis.readFully(b, off, len);
}
public int skipBytes (int n) throws IOException {
return dis.skipBytes(n);
}
public void write (int b) throws IOException {
dos.write(b);
};
public void write (byte b[]) throws IOException {
dos.write(b);
}
public void write (byte b[], int off, int len) throws IOException {
dos.write(b, off, len);
}
public long getFilePointer () throws IOException {
return pos;
}
public void seek (long pos) throws IOException {
if (pos < 0) {
throw new IllegalArgumentException();
}
this.pos = (int)pos;
}
public long length () throws IOException {
return len;
}
public void setLength (long newLength) throws IOException {
if (len != newLength) {
consolidate();
if (data.length() > newLength) {
data = data.substring(0, (int)newLength);
len = (int)newLength;
} else {
// System.out.println("padding " + (newLength - len) + " zeros in setLength to " + newLength);
while (len < newLength) {
write(0);
}
}
}
}
public void close () throws IOException {
if (data != null) {
flush();
data = null;
}
}
void consolidate () {
if (newData == null) {
return;
}
// System.out.println("consolidate(); ndp: " + newDataPos + " nd-len: " + newData.length());
if (data.length() < newDataPos) {
StringBuilder filler = new StringBuilder();
while (data.length() + filler.length() < newDataPos) {
filler.append('\0');
}
// System.out.println("padding " + (filler.length()) + " zeros in consolidate ");
data += filler.toString();
}
int p2 = newDataPos + newData.length();
data = data.substring(0, newDataPos) + newData.toString() + (p2 < data.length() ? data.substring(p2) : "");
newData = null;
}
void flush () throws IOException {
if (!dirty) {
return;
}
consolidate();
File.LocalStorage.setItem(name, btoa(data));
dirty = false;
}
public final boolean readBoolean () throws IOException {
return dis.readBoolean();
}
public final byte readByte () throws IOException {
return dis.readByte();
}
public final int readUnsignedByte () throws IOException {
return dis.readUnsignedByte();
}
public final short readShort () throws IOException {
return dis.readShort();
}
public final int readUnsignedShort () throws IOException {
return dis.readUnsignedShort();
}
public final char readChar () throws IOException {
return dis.readChar();
}
public final int readInt () throws IOException {
return dis.readInt();
}
public final long readLong () throws IOException {
return dis.readLong();
}
public final float readFloat () throws IOException {
return dis.readFloat();
}
public final double readDouble () throws IOException {
return dis.readDouble();
}
public final String readLine () throws IOException {
return dis.readLine();
}
public final String readUTF () throws IOException {
return dis.readUTF();
}
public final void writeBoolean (boolean v) throws IOException {
dos.writeBoolean(v);
}
public final void writeByte (int v) throws IOException {
dos.writeByte(v);
}
public final void writeShort (int v) throws IOException {
dos.writeShort(v);
}
public final void writeChar (int v) throws IOException {
dos.writeChar(v);
}
public final void writeInt (int v) throws IOException {
dos.writeInt(v);
}
public final void writeLong (long v) throws IOException {
dos.writeLong(v);
}
public final void writeFloat (float v) throws IOException {
dos.writeFloat(v);
}
public final void writeDouble (double v) throws IOException {
dos.writeDouble(v);
}
public final void writeBytes (String s) throws IOException {
dos.writeBytes(s);
}
public final void writeChars (String s) throws IOException {
dos.writeChars(s);
}
public final void writeUTF (String str) throws IOException {
dos.writeUTF(str);
}
public final FileChannel getChannel () throws IOException {
return null;
}
class RafInputStream extends InputStream {
@Override
public int read () throws IOException {
if (pos >= len) {
return -1;
} else {
consolidate();
return data.charAt(pos++);
// int p2 = (pos << 1);
// int result = Character.digit(data.charAt(p2), 16) * 16 +
// Character.digit(data.charAt(p2 + 1), 16);
// pos++;
// return result;
}
}
}
class RafOutputStream extends OutputStream {
public void write (int b) throws IOException {
if (!writeable) {
throw new IOException("not writeable");
}
if (newData == null) {
newDataPos = pos;
newData = new StringBuilder();
// System.out.println("no buf; newDataPos: " + pos);
} else if (newDataPos + newData.length() != pos) {
consolidate();
newDataPos = pos;
newData = new StringBuilder();
// System.out.println("pos mismatch; newDataPos: " + pos);
}
newData.append((char)(b & 255));
// newData.append("" + Character.forDigit((b >> 4) & 15, 16) +
// Character.forDigit(b & 15, 16));
pos++;
len = Math.max(pos, len);
dirty = true;
}
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-tools/src/com/badlogic/gdx/tools/hiero/Kerning.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tools.hiero;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.IntIntMap;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
/** Reads a TTF font file and provides access to kerning information.
*
* Thanks to the Apache FOP project for their inspiring work!
*
* @author Nathan Sweet */
public class Kerning {
private TTFInputStream input;
private float scale;
private int headOffset = -1;
private int kernOffset = -1;
private int gposOffset = -1;
private IntIntMap kernings = new IntIntMap();
/** @param inputStream The data for the TTF font.
* @param fontSize The font size to use to determine kerning pixel offsets.
* @throws IOException If the font could not be read. */
public void load (InputStream inputStream, int fontSize) throws IOException {
if (inputStream == null) throw new IllegalArgumentException("inputStream cannot be null.");
input = new TTFInputStream(inputStream);
inputStream.close();
readTableDirectory();
if (headOffset == -1) throw new IOException("HEAD table not found.");
readHEAD(fontSize);
// By reading the 'kern' table last, it takes precedence over the 'GPOS' table. We are more likely to interpret
// the GPOS table incorrectly because we ignore most of it, since BMFont doesn't support its features.
if (gposOffset != -1) {
input.seek(gposOffset);
readGPOS();
}
if (kernOffset != -1) {
input.seek(kernOffset);
readKERN();
}
input.close();
input = null;
}
/** @return A map from pairs of glyph codes to their kerning in pixels. Each map key encodes two glyph codes: the high 16 bits
* form the first glyph code, and the low 16 bits form the second. */
public IntIntMap getKernings () {
return kernings;
}
private void storeKerningOffset (int firstGlyphCode, int secondGlyphCode, int offset) {
// Scale the offset values using the font size.
int value = Math.round(offset * scale);
if (value == 0) {
return;
}
int key = (firstGlyphCode << 16) | secondGlyphCode;
kernings.put(key, value);
}
private void readTableDirectory () throws IOException {
input.skip(4);
int tableCount = input.readUnsignedShort();
input.skip(6);
byte[] tagBytes = new byte[4];
for (int i = 0; i < tableCount; i++) {
tagBytes[0] = input.readByte();
tagBytes[1] = input.readByte();
tagBytes[2] = input.readByte();
tagBytes[3] = input.readByte();
input.skip(4);
int offset = (int)input.readUnsignedLong();
input.skip(4);
String tag = new String(tagBytes, "ISO-8859-1");
if (tag.equals("head")) {
headOffset = offset;
} else if (tag.equals("kern")) {
kernOffset = offset;
} else if (tag.equals("GPOS")) {
gposOffset = offset;
}
}
}
private void readHEAD (int fontSize) throws IOException {
input.seek(headOffset + 2 * 4 + 2 * 4 + 2);
int unitsPerEm = input.readUnsignedShort();
scale = (float)fontSize / unitsPerEm;
}
private void readKERN () throws IOException {
input.seek(kernOffset + 2);
for (int subTableCount = input.readUnsignedShort(); subTableCount > 0; subTableCount--) {
input.skip(2 * 2);
int tupleIndex = input.readUnsignedShort();
if (!((tupleIndex & 1) != 0) || (tupleIndex & 2) != 0 || (tupleIndex & 4) != 0) return;
if (tupleIndex >> 8 != 0) continue;
int kerningCount = input.readUnsignedShort();
input.skip(3 * 2);
while (kerningCount-- > 0) {
int firstGlyphCode = input.readUnsignedShort();
int secondGlyphCode = input.readUnsignedShort();
int offset = (int)input.readShort();
storeKerningOffset(firstGlyphCode, secondGlyphCode, offset);
}
}
}
private void readGPOS () throws IOException {
// See https://www.microsoft.com/typography/otspec/gpos.htm for the format and semantics.
// Useful tools are ttfdump and showttf.
input.seek(gposOffset + 4 + 2 + 2);
int lookupListOffset = input.readUnsignedShort();
input.seek(gposOffset + lookupListOffset);
int lookupListPosition = input.getPosition();
int lookupCount = input.readUnsignedShort();
int[] lookupOffsets = input.readUnsignedShortArray(lookupCount);
for (int i = 0; i < lookupCount; i++) {
int lookupPosition = lookupListPosition + lookupOffsets[i];
input.seek(lookupPosition);
int type = input.readUnsignedShort();
readSubtables(type, lookupPosition);
}
}
private void readSubtables (int type, int lookupPosition) throws IOException {
input.skip(2);
int subTableCount = input.readUnsignedShort();
int[] subTableOffsets = input.readUnsignedShortArray(subTableCount);
for (int i = 0; i < subTableCount; i++) {
int subTablePosition = lookupPosition + subTableOffsets[i];
readSubtable(type, subTablePosition);
}
}
private void readSubtable (int type, int subTablePosition) throws IOException {
input.seek(subTablePosition);
if (type == 2) {
readPairAdjustmentSubtable(subTablePosition);
} else if (type == 9) {
readExtensionPositioningSubtable(subTablePosition);
}
}
private void readPairAdjustmentSubtable (int subTablePosition) throws IOException {
int type = input.readUnsignedShort();
if (type == 1) {
readPairPositioningAdjustmentFormat1(subTablePosition);
} else if (type == 2) {
readPairPositioningAdjustmentFormat2(subTablePosition);
}
}
private void readExtensionPositioningSubtable (int subTablePosition) throws IOException {
int type = input.readUnsignedShort();
if (type == 1) {
readExtensionPositioningFormat1(subTablePosition);
}
}
private void readPairPositioningAdjustmentFormat1 (long subTablePosition) throws IOException {
int coverageOffset = input.readUnsignedShort();
int valueFormat1 = input.readUnsignedShort();
int valueFormat2 = input.readUnsignedShort();
int pairSetCount = input.readUnsignedShort();
int[] pairSetOffsets = input.readUnsignedShortArray(pairSetCount);
input.seek((int)(subTablePosition + coverageOffset));
int[] coverage = readCoverageTable();
// The two should be equal, but just in case they're not, we can still do something sensible.
pairSetCount = Math.min(pairSetCount, coverage.length);
for (int i = 0; i < pairSetCount; i++) {
int firstGlyph = coverage[i];
input.seek((int)(subTablePosition + pairSetOffsets[i]));
int pairValueCount = input.readUnsignedShort();
for (int j = 0; j < pairValueCount; j++) {
int secondGlyph = input.readUnsignedShort();
int xAdvance1 = readXAdvanceFromValueRecord(valueFormat1);
readXAdvanceFromValueRecord(valueFormat2); // Value2
if (xAdvance1 != 0) {
storeKerningOffset(firstGlyph, secondGlyph, xAdvance1);
}
}
}
}
private void readPairPositioningAdjustmentFormat2 (int subTablePosition) throws IOException {
int coverageOffset = input.readUnsignedShort();
int valueFormat1 = input.readUnsignedShort();
int valueFormat2 = input.readUnsignedShort();
int classDefOffset1 = input.readUnsignedShort();
int classDefOffset2 = input.readUnsignedShort();
int class1Count = input.readUnsignedShort();
int class2Count = input.readUnsignedShort();
int position = input.getPosition();
input.seek((int)(subTablePosition + coverageOffset));
int[] coverage = readCoverageTable();
input.seek(position);
IntArray[] glyphsByClass1 = readClassDefinition(subTablePosition + classDefOffset1, class1Count);
IntArray[] glyphsByClass2 = readClassDefinition(subTablePosition + classDefOffset2, class2Count);
input.seek(position);
for (int i = 0; i < coverage.length; i++) {
int glyph = coverage[i];
boolean found = false;
for (int j = 1; j < class1Count && !found; j++) {
found = glyphsByClass1[j].contains(glyph);
}
if (!found) {
glyphsByClass1[0].add(glyph);
}
}
for (int i = 0; i < class1Count; i++) {
for (int j = 0; j < class2Count; j++) {
int xAdvance1 = readXAdvanceFromValueRecord(valueFormat1);
readXAdvanceFromValueRecord(valueFormat2); // Value2
if (xAdvance1 == 0) continue;
for (int k = 0; k < glyphsByClass1[i].size; k++) {
int glyph1 = glyphsByClass1[i].items[k];
for (int l = 0; l < glyphsByClass2[j].size; l++) {
int glyph2 = glyphsByClass2[j].items[l];
storeKerningOffset(glyph1, glyph2, xAdvance1);
}
}
}
}
}
private void readExtensionPositioningFormat1 (int subTablePosition) throws IOException {
int lookupType = input.readUnsignedShort();
int lookupPosition = subTablePosition + (int)input.readUnsignedLong();
readSubtable(lookupType, lookupPosition);
}
private IntArray[] readClassDefinition (int position, int classCount) throws IOException {
input.seek(position);
IntArray[] glyphsByClass = new IntArray[classCount];
for (int i = 0; i < classCount; i++) {
glyphsByClass[i] = new IntArray();
}
int classFormat = input.readUnsignedShort();
if (classFormat == 1) {
readClassDefinitionFormat1(glyphsByClass);
} else if (classFormat == 2) {
readClassDefinitionFormat2(glyphsByClass);
} else {
throw new IOException("Unknown class definition table type " + classFormat);
}
return glyphsByClass;
}
private void readClassDefinitionFormat1 (IntArray[] glyphsByClass) throws IOException {
int startGlyph = input.readUnsignedShort();
int glyphCount = input.readUnsignedShort();
int[] classValueArray = input.readUnsignedShortArray(glyphCount);
for (int i = 0; i < glyphCount; i++) {
int glyph = startGlyph + i;
int glyphClass = classValueArray[i];
if (glyphClass < glyphsByClass.length) {
glyphsByClass[glyphClass].add(glyph);
}
}
}
private void readClassDefinitionFormat2 (IntArray[] glyphsByClass) throws IOException {
int classRangeCount = input.readUnsignedShort();
for (int i = 0; i < classRangeCount; i++) {
int start = input.readUnsignedShort();
int end = input.readUnsignedShort();
int glyphClass = input.readUnsignedShort();
if (glyphClass < glyphsByClass.length) {
for (int glyph = start; glyph <= end; glyph++) {
glyphsByClass[glyphClass].add(glyph);
}
}
}
}
private int[] readCoverageTable () throws IOException {
int format = input.readUnsignedShort();
if (format == 1) {
int glyphCount = input.readUnsignedShort();
int[] glyphArray = input.readUnsignedShortArray(glyphCount);
return glyphArray;
} else if (format == 2) {
int rangeCount = input.readUnsignedShort();
IntArray glyphArray = new IntArray();
for (int i = 0; i < rangeCount; i++) {
int start = input.readUnsignedShort();
int end = input.readUnsignedShort();
input.skip(2);
for (int glyph = start; glyph <= end; glyph++) {
glyphArray.add(glyph);
}
}
return glyphArray.shrink();
}
throw new IOException("Unknown coverage table format " + format);
}
private int readXAdvanceFromValueRecord (int valueFormat) throws IOException {
int xAdvance = 0;
for (int mask = 1; mask <= 0x8000 && mask <= valueFormat; mask <<= 1) {
if ((valueFormat & mask) != 0) {
int value = (int)input.readShort();
if (mask == 0x0004) {
xAdvance = value;
}
}
}
return xAdvance;
}
private static class TTFInputStream extends ByteArrayInputStream {
public TTFInputStream (InputStream input) throws IOException {
super(readAllBytes(input));
}
private static byte[] readAllBytes (InputStream input) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int numRead;
byte[] buffer = new byte[16384];
while ((numRead = input.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, numRead);
}
return out.toByteArray();
}
public int getPosition () {
return pos;
}
public void seek (int position) {
pos = position;
}
public int readUnsignedByte () throws IOException {
int b = read();
if (b == -1) throw new EOFException("Unexpected end of file.");
return b;
}
public byte readByte () throws IOException {
return (byte)readUnsignedByte();
}
public int readUnsignedShort () throws IOException {
return (readUnsignedByte() << 8) + readUnsignedByte();
}
public short readShort () throws IOException {
return (short)readUnsignedShort();
}
public long readUnsignedLong () throws IOException {
long value = readUnsignedByte();
value = (value << 8) + readUnsignedByte();
value = (value << 8) + readUnsignedByte();
value = (value << 8) + readUnsignedByte();
return value;
}
public int[] readUnsignedShortArray (int count) throws IOException {
int[] shorts = new int[count];
for (int i = 0; i < count; i++) {
shorts[i] = readUnsignedShort();
}
return shorts;
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tools.hiero;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.IntIntMap;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
/** Reads a TTF font file and provides access to kerning information.
*
* Thanks to the Apache FOP project for their inspiring work!
*
* @author Nathan Sweet */
public class Kerning {
private TTFInputStream input;
private float scale;
private int headOffset = -1;
private int kernOffset = -1;
private int gposOffset = -1;
private IntIntMap kernings = new IntIntMap();
/** @param inputStream The data for the TTF font.
* @param fontSize The font size to use to determine kerning pixel offsets.
* @throws IOException If the font could not be read. */
public void load (InputStream inputStream, int fontSize) throws IOException {
if (inputStream == null) throw new IllegalArgumentException("inputStream cannot be null.");
input = new TTFInputStream(inputStream);
inputStream.close();
readTableDirectory();
if (headOffset == -1) throw new IOException("HEAD table not found.");
readHEAD(fontSize);
// By reading the 'kern' table last, it takes precedence over the 'GPOS' table. We are more likely to interpret
// the GPOS table incorrectly because we ignore most of it, since BMFont doesn't support its features.
if (gposOffset != -1) {
input.seek(gposOffset);
readGPOS();
}
if (kernOffset != -1) {
input.seek(kernOffset);
readKERN();
}
input.close();
input = null;
}
/** @return A map from pairs of glyph codes to their kerning in pixels. Each map key encodes two glyph codes: the high 16 bits
* form the first glyph code, and the low 16 bits form the second. */
public IntIntMap getKernings () {
return kernings;
}
private void storeKerningOffset (int firstGlyphCode, int secondGlyphCode, int offset) {
// Scale the offset values using the font size.
int value = Math.round(offset * scale);
if (value == 0) {
return;
}
int key = (firstGlyphCode << 16) | secondGlyphCode;
kernings.put(key, value);
}
private void readTableDirectory () throws IOException {
input.skip(4);
int tableCount = input.readUnsignedShort();
input.skip(6);
byte[] tagBytes = new byte[4];
for (int i = 0; i < tableCount; i++) {
tagBytes[0] = input.readByte();
tagBytes[1] = input.readByte();
tagBytes[2] = input.readByte();
tagBytes[3] = input.readByte();
input.skip(4);
int offset = (int)input.readUnsignedLong();
input.skip(4);
String tag = new String(tagBytes, "ISO-8859-1");
if (tag.equals("head")) {
headOffset = offset;
} else if (tag.equals("kern")) {
kernOffset = offset;
} else if (tag.equals("GPOS")) {
gposOffset = offset;
}
}
}
private void readHEAD (int fontSize) throws IOException {
input.seek(headOffset + 2 * 4 + 2 * 4 + 2);
int unitsPerEm = input.readUnsignedShort();
scale = (float)fontSize / unitsPerEm;
}
private void readKERN () throws IOException {
input.seek(kernOffset + 2);
for (int subTableCount = input.readUnsignedShort(); subTableCount > 0; subTableCount--) {
input.skip(2 * 2);
int tupleIndex = input.readUnsignedShort();
if (!((tupleIndex & 1) != 0) || (tupleIndex & 2) != 0 || (tupleIndex & 4) != 0) return;
if (tupleIndex >> 8 != 0) continue;
int kerningCount = input.readUnsignedShort();
input.skip(3 * 2);
while (kerningCount-- > 0) {
int firstGlyphCode = input.readUnsignedShort();
int secondGlyphCode = input.readUnsignedShort();
int offset = (int)input.readShort();
storeKerningOffset(firstGlyphCode, secondGlyphCode, offset);
}
}
}
private void readGPOS () throws IOException {
// See https://www.microsoft.com/typography/otspec/gpos.htm for the format and semantics.
// Useful tools are ttfdump and showttf.
input.seek(gposOffset + 4 + 2 + 2);
int lookupListOffset = input.readUnsignedShort();
input.seek(gposOffset + lookupListOffset);
int lookupListPosition = input.getPosition();
int lookupCount = input.readUnsignedShort();
int[] lookupOffsets = input.readUnsignedShortArray(lookupCount);
for (int i = 0; i < lookupCount; i++) {
int lookupPosition = lookupListPosition + lookupOffsets[i];
input.seek(lookupPosition);
int type = input.readUnsignedShort();
readSubtables(type, lookupPosition);
}
}
private void readSubtables (int type, int lookupPosition) throws IOException {
input.skip(2);
int subTableCount = input.readUnsignedShort();
int[] subTableOffsets = input.readUnsignedShortArray(subTableCount);
for (int i = 0; i < subTableCount; i++) {
int subTablePosition = lookupPosition + subTableOffsets[i];
readSubtable(type, subTablePosition);
}
}
private void readSubtable (int type, int subTablePosition) throws IOException {
input.seek(subTablePosition);
if (type == 2) {
readPairAdjustmentSubtable(subTablePosition);
} else if (type == 9) {
readExtensionPositioningSubtable(subTablePosition);
}
}
private void readPairAdjustmentSubtable (int subTablePosition) throws IOException {
int type = input.readUnsignedShort();
if (type == 1) {
readPairPositioningAdjustmentFormat1(subTablePosition);
} else if (type == 2) {
readPairPositioningAdjustmentFormat2(subTablePosition);
}
}
private void readExtensionPositioningSubtable (int subTablePosition) throws IOException {
int type = input.readUnsignedShort();
if (type == 1) {
readExtensionPositioningFormat1(subTablePosition);
}
}
private void readPairPositioningAdjustmentFormat1 (long subTablePosition) throws IOException {
int coverageOffset = input.readUnsignedShort();
int valueFormat1 = input.readUnsignedShort();
int valueFormat2 = input.readUnsignedShort();
int pairSetCount = input.readUnsignedShort();
int[] pairSetOffsets = input.readUnsignedShortArray(pairSetCount);
input.seek((int)(subTablePosition + coverageOffset));
int[] coverage = readCoverageTable();
// The two should be equal, but just in case they're not, we can still do something sensible.
pairSetCount = Math.min(pairSetCount, coverage.length);
for (int i = 0; i < pairSetCount; i++) {
int firstGlyph = coverage[i];
input.seek((int)(subTablePosition + pairSetOffsets[i]));
int pairValueCount = input.readUnsignedShort();
for (int j = 0; j < pairValueCount; j++) {
int secondGlyph = input.readUnsignedShort();
int xAdvance1 = readXAdvanceFromValueRecord(valueFormat1);
readXAdvanceFromValueRecord(valueFormat2); // Value2
if (xAdvance1 != 0) {
storeKerningOffset(firstGlyph, secondGlyph, xAdvance1);
}
}
}
}
private void readPairPositioningAdjustmentFormat2 (int subTablePosition) throws IOException {
int coverageOffset = input.readUnsignedShort();
int valueFormat1 = input.readUnsignedShort();
int valueFormat2 = input.readUnsignedShort();
int classDefOffset1 = input.readUnsignedShort();
int classDefOffset2 = input.readUnsignedShort();
int class1Count = input.readUnsignedShort();
int class2Count = input.readUnsignedShort();
int position = input.getPosition();
input.seek((int)(subTablePosition + coverageOffset));
int[] coverage = readCoverageTable();
input.seek(position);
IntArray[] glyphsByClass1 = readClassDefinition(subTablePosition + classDefOffset1, class1Count);
IntArray[] glyphsByClass2 = readClassDefinition(subTablePosition + classDefOffset2, class2Count);
input.seek(position);
for (int i = 0; i < coverage.length; i++) {
int glyph = coverage[i];
boolean found = false;
for (int j = 1; j < class1Count && !found; j++) {
found = glyphsByClass1[j].contains(glyph);
}
if (!found) {
glyphsByClass1[0].add(glyph);
}
}
for (int i = 0; i < class1Count; i++) {
for (int j = 0; j < class2Count; j++) {
int xAdvance1 = readXAdvanceFromValueRecord(valueFormat1);
readXAdvanceFromValueRecord(valueFormat2); // Value2
if (xAdvance1 == 0) continue;
for (int k = 0; k < glyphsByClass1[i].size; k++) {
int glyph1 = glyphsByClass1[i].items[k];
for (int l = 0; l < glyphsByClass2[j].size; l++) {
int glyph2 = glyphsByClass2[j].items[l];
storeKerningOffset(glyph1, glyph2, xAdvance1);
}
}
}
}
}
private void readExtensionPositioningFormat1 (int subTablePosition) throws IOException {
int lookupType = input.readUnsignedShort();
int lookupPosition = subTablePosition + (int)input.readUnsignedLong();
readSubtable(lookupType, lookupPosition);
}
private IntArray[] readClassDefinition (int position, int classCount) throws IOException {
input.seek(position);
IntArray[] glyphsByClass = new IntArray[classCount];
for (int i = 0; i < classCount; i++) {
glyphsByClass[i] = new IntArray();
}
int classFormat = input.readUnsignedShort();
if (classFormat == 1) {
readClassDefinitionFormat1(glyphsByClass);
} else if (classFormat == 2) {
readClassDefinitionFormat2(glyphsByClass);
} else {
throw new IOException("Unknown class definition table type " + classFormat);
}
return glyphsByClass;
}
private void readClassDefinitionFormat1 (IntArray[] glyphsByClass) throws IOException {
int startGlyph = input.readUnsignedShort();
int glyphCount = input.readUnsignedShort();
int[] classValueArray = input.readUnsignedShortArray(glyphCount);
for (int i = 0; i < glyphCount; i++) {
int glyph = startGlyph + i;
int glyphClass = classValueArray[i];
if (glyphClass < glyphsByClass.length) {
glyphsByClass[glyphClass].add(glyph);
}
}
}
private void readClassDefinitionFormat2 (IntArray[] glyphsByClass) throws IOException {
int classRangeCount = input.readUnsignedShort();
for (int i = 0; i < classRangeCount; i++) {
int start = input.readUnsignedShort();
int end = input.readUnsignedShort();
int glyphClass = input.readUnsignedShort();
if (glyphClass < glyphsByClass.length) {
for (int glyph = start; glyph <= end; glyph++) {
glyphsByClass[glyphClass].add(glyph);
}
}
}
}
private int[] readCoverageTable () throws IOException {
int format = input.readUnsignedShort();
if (format == 1) {
int glyphCount = input.readUnsignedShort();
int[] glyphArray = input.readUnsignedShortArray(glyphCount);
return glyphArray;
} else if (format == 2) {
int rangeCount = input.readUnsignedShort();
IntArray glyphArray = new IntArray();
for (int i = 0; i < rangeCount; i++) {
int start = input.readUnsignedShort();
int end = input.readUnsignedShort();
input.skip(2);
for (int glyph = start; glyph <= end; glyph++) {
glyphArray.add(glyph);
}
}
return glyphArray.shrink();
}
throw new IOException("Unknown coverage table format " + format);
}
private int readXAdvanceFromValueRecord (int valueFormat) throws IOException {
int xAdvance = 0;
for (int mask = 1; mask <= 0x8000 && mask <= valueFormat; mask <<= 1) {
if ((valueFormat & mask) != 0) {
int value = (int)input.readShort();
if (mask == 0x0004) {
xAdvance = value;
}
}
}
return xAdvance;
}
private static class TTFInputStream extends ByteArrayInputStream {
public TTFInputStream (InputStream input) throws IOException {
super(readAllBytes(input));
}
private static byte[] readAllBytes (InputStream input) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int numRead;
byte[] buffer = new byte[16384];
while ((numRead = input.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, numRead);
}
return out.toByteArray();
}
public int getPosition () {
return pos;
}
public void seek (int position) {
pos = position;
}
public int readUnsignedByte () throws IOException {
int b = read();
if (b == -1) throw new EOFException("Unexpected end of file.");
return b;
}
public byte readByte () throws IOException {
return (byte)readUnsignedByte();
}
public int readUnsignedShort () throws IOException {
return (readUnsignedByte() << 8) + readUnsignedByte();
}
public short readShort () throws IOException {
return (short)readUnsignedShort();
}
public long readUnsignedLong () throws IOException {
long value = readUnsignedByte();
value = (value << 8) + readUnsignedByte();
value = (value << 8) + readUnsignedByte();
value = (value << 8) + readUnsignedByte();
return value;
}
public int[] readUnsignedShortArray (int count) throws IOException {
int[] shorts = new int[count];
for (int i = 0; i < count; i++) {
shorts[i] = readUnsignedShort();
}
return shorts;
}
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/common/IViewportTransform.java | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.common;
/** This is the viewport transform used from drawing. Use yFlip if you are drawing from the top-left corner.
*
* @author Daniel */
public interface IViewportTransform {
/** @return if the transform flips the y axis */
boolean isYFlip ();
/** @param yFlip if we flip the y axis when transforming */
void setYFlip (boolean yFlip);
/** This is the half-width and half-height. This should be the actual half-width and half-height, not anything transformed or
* scaled. Not a copy. */
Vec2 getExtents ();
/** This sets the half-width and half-height. This should be the actual half-width and half-height, not anything transformed or
* scaled. */
void setExtents (Vec2 extents);
/** This sets the half-width and half-height of the viewport. This should be the actual half-width and half-height, not
* anything transformed or scaled. */
void setExtents (float halfWidth, float halfHeight);
/** center of the viewport. Not a copy. */
Vec2 getCenter ();
/** sets the center of the viewport. */
void setCenter (Vec2 pos);
/** sets the center of the viewport. */
void setCenter (float x, float y);
/** Sets the transform's center to the given x and y coordinates, and using the given scale. */
void setCamera (float x, float y, float scale);
/** Transforms the given directional vector by the viewport transform (not positional) */
void getWorldVectorToScreen (Vec2 world, Vec2 screen);
/** Transforms the given directional screen vector back to the world direction. */
void getScreenVectorToWorld (Vec2 screen, Vec2 world);
Mat22 getMat22Representation ();
/** takes the world coordinate (world) puts the corresponding screen coordinate in screen. It should be safe to give the same
* object as both parameters. */
void getWorldToScreen (Vec2 world, Vec2 screen);
/** takes the screen coordinates (screen) and puts the corresponding world coordinates in world. It should be safe to give the
* same object as both parameters. */
void getScreenToWorld (Vec2 screen, Vec2 world);
/** Multiplies the viewport transform by the given Mat22 */
void mulByTransform (Mat22 transform);
}
| /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.common;
/** This is the viewport transform used from drawing. Use yFlip if you are drawing from the top-left corner.
*
* @author Daniel */
public interface IViewportTransform {
/** @return if the transform flips the y axis */
boolean isYFlip ();
/** @param yFlip if we flip the y axis when transforming */
void setYFlip (boolean yFlip);
/** This is the half-width and half-height. This should be the actual half-width and half-height, not anything transformed or
* scaled. Not a copy. */
Vec2 getExtents ();
/** This sets the half-width and half-height. This should be the actual half-width and half-height, not anything transformed or
* scaled. */
void setExtents (Vec2 extents);
/** This sets the half-width and half-height of the viewport. This should be the actual half-width and half-height, not
* anything transformed or scaled. */
void setExtents (float halfWidth, float halfHeight);
/** center of the viewport. Not a copy. */
Vec2 getCenter ();
/** sets the center of the viewport. */
void setCenter (Vec2 pos);
/** sets the center of the viewport. */
void setCenter (float x, float y);
/** Sets the transform's center to the given x and y coordinates, and using the given scale. */
void setCamera (float x, float y, float scale);
/** Transforms the given directional vector by the viewport transform (not positional) */
void getWorldVectorToScreen (Vec2 world, Vec2 screen);
/** Transforms the given directional screen vector back to the world direction. */
void getScreenVectorToWorld (Vec2 screen, Vec2 world);
Mat22 getMat22Representation ();
/** takes the world coordinate (world) puts the corresponding screen coordinate in screen. It should be safe to give the same
* object as both parameters. */
void getWorldToScreen (Vec2 world, Vec2 screen);
/** takes the screen coordinates (screen) and puts the corresponding world coordinates in world. It should be safe to give the
* same object as both parameters. */
void getScreenToWorld (Vec2 screen, Vec2 world);
/** Multiplies the viewport transform by the given Mat22 */
void mulByTransform (Mat22 transform);
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/linearmath/com/badlogic/gdx/physics/bullet/linearmath/SWIGTYPE_p_f_size_t__p_void.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.linearmath;
public class SWIGTYPE_p_f_size_t__p_void {
private transient long swigCPtr;
protected SWIGTYPE_p_f_size_t__p_void (long cPtr, @SuppressWarnings("unused") boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_f_size_t__p_void () {
swigCPtr = 0;
}
protected static long getCPtr (SWIGTYPE_p_f_size_t__p_void obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.linearmath;
public class SWIGTYPE_p_f_size_t__p_void {
private transient long swigCPtr;
protected SWIGTYPE_p_f_size_t__p_void (long cPtr, @SuppressWarnings("unused") boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_f_size_t__p_void () {
swigCPtr = 0;
}
protected static long getCPtr (SWIGTYPE_p_f_size_t__p_void obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/LongToByteBufferAdapter.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio;
//import org.apache.harmony.nio.internal.DirectBuffer;
//import org.apache.harmony.luni.platform.PlatformAddress;
/** This class wraps a byte buffer to be a long buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the
* adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position
* and limit.</li>
* </ul>
* </p>
*/
final class LongToByteBufferAdapter extends LongBuffer {// implements DirectBuffer {
static LongBuffer wrap (ByteBuffer byteBuffer) {
return new LongToByteBufferAdapter(byteBuffer.slice());
}
private final ByteBuffer byteBuffer;
LongToByteBufferAdapter (ByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 3));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
}
// public int getByteCapacity() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getByteCapacity();
// }
// assert false : byteBuffer;
// return -1;
// }
//
// public PlatformAddress getEffectiveAddress() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getEffectiveAddress();
// }
// assert false : byteBuffer;
// return null;
// }
//
// public PlatformAddress getBaseAddress() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getBaseAddress();
// }
// assert false : byteBuffer;
// return null;
// }
//
// public boolean isAddressValid() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).isAddressValid();
// }
// assert false : byteBuffer;
// return false;
// }
//
// public void addressValidityCheck() {
// if (byteBuffer instanceof DirectBuffer) {
// ((DirectBuffer) byteBuffer).addressValidityCheck();
// } else {
// assert false : byteBuffer;
// }
// }
//
// public void free() {
// if (byteBuffer instanceof DirectBuffer) {
// ((DirectBuffer) byteBuffer).free();
// } else {
// assert false : byteBuffer;
// }
// }
@Override
public LongBuffer asReadOnlyBuffer () {
LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public LongBuffer compact () {
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
byteBuffer.limit(limit << 3);
byteBuffer.position(position << 3);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public LongBuffer duplicate () {
LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public long get () {
if (position == limit) {
throw new BufferUnderflowException();
}
return byteBuffer.getLong(position++ << 3);
}
@Override
public long get (int index) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
return byteBuffer.getLong(index << 3);
}
@Override
public boolean isDirect () {
return byteBuffer.isDirect();
}
@Override
public boolean isReadOnly () {
return byteBuffer.isReadOnly();
}
@Override
public ByteOrder order () {
return byteBuffer.order();
}
@Override
protected long[] protectedArray () {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset () {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray () {
return false;
}
@Override
public LongBuffer put (long c) {
if (position == limit) {
throw new BufferOverflowException();
}
byteBuffer.putLong(position++ << 3, c);
return this;
}
@Override
public LongBuffer put (int index, long c) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
byteBuffer.putLong(index << 3, c);
return this;
}
@Override
public LongBuffer slice () {
byteBuffer.limit(limit << 3);
byteBuffer.position(position << 3);
LongBuffer result = new LongToByteBufferAdapter(byteBuffer.slice());
byteBuffer.clear();
return result;
}
}
| /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio;
//import org.apache.harmony.nio.internal.DirectBuffer;
//import org.apache.harmony.luni.platform.PlatformAddress;
/** This class wraps a byte buffer to be a long buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the
* adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position
* and limit.</li>
* </ul>
* </p>
*/
final class LongToByteBufferAdapter extends LongBuffer {// implements DirectBuffer {
static LongBuffer wrap (ByteBuffer byteBuffer) {
return new LongToByteBufferAdapter(byteBuffer.slice());
}
private final ByteBuffer byteBuffer;
LongToByteBufferAdapter (ByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 3));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
}
// public int getByteCapacity() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getByteCapacity();
// }
// assert false : byteBuffer;
// return -1;
// }
//
// public PlatformAddress getEffectiveAddress() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getEffectiveAddress();
// }
// assert false : byteBuffer;
// return null;
// }
//
// public PlatformAddress getBaseAddress() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).getBaseAddress();
// }
// assert false : byteBuffer;
// return null;
// }
//
// public boolean isAddressValid() {
// if (byteBuffer instanceof DirectBuffer) {
// return ((DirectBuffer) byteBuffer).isAddressValid();
// }
// assert false : byteBuffer;
// return false;
// }
//
// public void addressValidityCheck() {
// if (byteBuffer instanceof DirectBuffer) {
// ((DirectBuffer) byteBuffer).addressValidityCheck();
// } else {
// assert false : byteBuffer;
// }
// }
//
// public void free() {
// if (byteBuffer instanceof DirectBuffer) {
// ((DirectBuffer) byteBuffer).free();
// } else {
// assert false : byteBuffer;
// }
// }
@Override
public LongBuffer asReadOnlyBuffer () {
LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer.asReadOnlyBuffer());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public LongBuffer compact () {
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
}
byteBuffer.limit(limit << 3);
byteBuffer.position(position << 3);
byteBuffer.compact();
byteBuffer.clear();
position = limit - position;
limit = capacity;
mark = UNSET_MARK;
return this;
}
@Override
public LongBuffer duplicate () {
LongToByteBufferAdapter buf = new LongToByteBufferAdapter(byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public long get () {
if (position == limit) {
throw new BufferUnderflowException();
}
return byteBuffer.getLong(position++ << 3);
}
@Override
public long get (int index) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
return byteBuffer.getLong(index << 3);
}
@Override
public boolean isDirect () {
return byteBuffer.isDirect();
}
@Override
public boolean isReadOnly () {
return byteBuffer.isReadOnly();
}
@Override
public ByteOrder order () {
return byteBuffer.order();
}
@Override
protected long[] protectedArray () {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset () {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray () {
return false;
}
@Override
public LongBuffer put (long c) {
if (position == limit) {
throw new BufferOverflowException();
}
byteBuffer.putLong(position++ << 3, c);
return this;
}
@Override
public LongBuffer put (int index, long c) {
if (index < 0 || index >= limit) {
throw new IndexOutOfBoundsException();
}
byteBuffer.putLong(index << 3, c);
return this;
}
@Override
public LongBuffer slice () {
byteBuffer.limit(limit << 3);
byteBuffer.position(position << 3);
LongBuffer result = new LongToByteBufferAdapter(byteBuffer.slice());
byteBuffer.clear();
return result;
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/Box2DCharacterControllerTest.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.WorldManifold;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
public class Box2DCharacterControllerTest extends GdxTest implements ApplicationListener {
final static float MAX_VELOCITY = 14f;
boolean jump = false;
World world;
Body player;
Fixture playerPhysicsFixture;
Fixture playerSensorFixture;
OrthographicCamera cam;
Box2DDebugRenderer renderer;
Array<Platform> platforms = new Array<Platform>();
Platform groundedPlatform = null;
float stillTime = 0;
long lastGroundTime = 0;
SpriteBatch batch;
BitmapFont font;
float accum = 0;
float TICK = 1 / 60f;
@Override
public void create () {
world = new World(new Vector2(0, -40), true);
renderer = new Box2DDebugRenderer();
cam = new OrthographicCamera(28, 20);
createWorld();
Gdx.input.setInputProcessor(this);
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/lsans-15.fnt"), false);
}
@Override
public void dispose () {
world.dispose();
renderer.dispose();
batch.dispose();
font.dispose();
}
private void createWorld () {
float y1 = 1; // (float)Math.random() * 0.1f + 1;
float y2 = y1;
for (int i = 0; i < 50; i++) {
Body ground = createEdge(BodyType.StaticBody, -50 + i * 2, y1, -50 + i * 2 + 2, y2, 0);
y1 = y2;
y2 = 1; // (float)Math.random() + 1;
}
Body box = createBox(BodyType.StaticBody, 1, 1, 0);
box.setTransform(30, 3, 0);
box = createBox(BodyType.StaticBody, 1.2f, 1.2f, 0);
box.setTransform(5, 2.4f, 0);
player = createPlayer();
player.setTransform(-40.0f, 4.0f, 0);
player.setFixedRotation(true);
for (int i = 0; i < 20; i++) {
box = createBox(BodyType.DynamicBody, (float)Math.random(), (float)Math.random(), 3);
box.setTransform((float)Math.random() * 10f - (float)Math.random() * 10f, (float)Math.random() * 10 + 6,
(float)(Math.random() * 2 * Math.PI));
}
for (int i = 0; i < 20; i++) {
Body circle = createCircle(BodyType.DynamicBody, (float)Math.random() * 0.5f, 3);
circle.setTransform((float)Math.random() * 10f - (float)Math.random() * 10f, (float)Math.random() * 10 + 6,
(float)(Math.random() * 2 * Math.PI));
}
platforms.add(new CirclePlatform(-24, -5, 10, (float)Math.PI / 4));
platforms.add(new MovingPlatform(-2, 3, 2, 0.5f, 2, 0, (float)Math.PI / 10f, 4));
platforms.add(new MovingPlatform(17, 2, 5, 0.5f, 2, 0, 0, 5));
platforms.add(new MovingPlatform(-7, 5, 2, 0.5f, -2, 2, 0, 8));
// platforms.add(new MovingPlatform(40, 3, 20, 0.5f, 0, 2, 5));
}
Body createBox (BodyType type, float width, float height, float density) {
BodyDef def = new BodyDef();
def.type = type;
Body box = world.createBody(def);
PolygonShape poly = new PolygonShape();
poly.setAsBox(width, height);
box.createFixture(poly, density);
poly.dispose();
return box;
}
private Body createEdge (BodyType type, float x1, float y1, float x2, float y2, float density) {
BodyDef def = new BodyDef();
def.type = type;
Body box = world.createBody(def);
EdgeShape poly = new EdgeShape();
poly.set(new Vector2(0, 0), new Vector2(x2 - x1, y2 - y1));
box.createFixture(poly, density);
box.setTransform(x1, y1, 0);
poly.dispose();
return box;
}
Body createCircle (BodyType type, float radius, float density) {
BodyDef def = new BodyDef();
def.type = type;
Body box = world.createBody(def);
CircleShape poly = new CircleShape();
poly.setRadius(radius);
box.createFixture(poly, density);
poly.dispose();
return box;
}
private Body createPlayer () {
BodyDef def = new BodyDef();
def.type = BodyType.DynamicBody;
Body box = world.createBody(def);
PolygonShape poly = new PolygonShape();
poly.setAsBox(0.45f, 1.4f);
playerPhysicsFixture = box.createFixture(poly, 1);
poly.dispose();
CircleShape circle = new CircleShape();
circle.setRadius(0.45f);
circle.setPosition(new Vector2(0, -1.4f));
playerSensorFixture = box.createFixture(circle, 0);
circle.dispose();
box.setBullet(true);
return box;
}
@Override
public void resume () {
}
@Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.position.set(player.getPosition().x, player.getPosition().y, 0);
cam.update();
renderer.render(world, cam.combined);
Vector2 vel = player.getLinearVelocity();
Vector2 pos = player.getPosition();
boolean grounded = isPlayerGrounded(Gdx.graphics.getDeltaTime());
if (grounded) {
lastGroundTime = TimeUtils.nanoTime();
} else {
if (TimeUtils.nanoTime() - lastGroundTime < 100000000) {
grounded = true;
}
}
// cap max velocity on x
if (Math.abs(vel.x) > MAX_VELOCITY) {
vel.x = Math.signum(vel.x) * MAX_VELOCITY;
player.setLinearVelocity(vel.x, vel.y);
}
// calculate stilltime & damp
if (!Gdx.input.isKeyPressed(Keys.A) && !Gdx.input.isKeyPressed(Keys.D)) {
stillTime += Gdx.graphics.getDeltaTime();
player.setLinearVelocity(vel.x * 0.9f, vel.y);
} else {
stillTime = 0;
}
// disable friction while jumping
if (!grounded) {
playerPhysicsFixture.setFriction(0f);
playerSensorFixture.setFriction(0f);
} else {
if (!Gdx.input.isKeyPressed(Keys.A) && !Gdx.input.isKeyPressed(Keys.D) && stillTime > 0.2) {
playerPhysicsFixture.setFriction(1000f);
playerSensorFixture.setFriction(1000f);
} else {
playerPhysicsFixture.setFriction(0.2f);
playerSensorFixture.setFriction(0.2f);
}
// dampen sudden changes in x/y of a MovingPlatform a little bit, otherwise
// character hops :)
if (groundedPlatform != null && groundedPlatform instanceof MovingPlatform
&& ((MovingPlatform)groundedPlatform).dist == 0) {
player.applyLinearImpulse(0, -24, pos.x, pos.y, true);
}
}
// since Box2D 2.2 we need to reset the friction of any existing contacts
Array<Contact> contacts = world.getContactList();
for (int i = 0; i < world.getContactCount(); i++) {
Contact contact = contacts.get(i);
contact.resetFriction();
}
// apply left impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Keys.A) && vel.x > -MAX_VELOCITY) {
player.applyLinearImpulse(-2f, 0, pos.x, pos.y, true);
}
// apply right impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Keys.D) && vel.x < MAX_VELOCITY) {
player.applyLinearImpulse(2f, 0, pos.x, pos.y, true);
}
// jump, but only when grounded
if (jump) {
jump = false;
if (grounded) {
player.setLinearVelocity(vel.x, 0);
System.out.println("jump before: " + player.getLinearVelocity());
player.setTransform(pos.x, pos.y + 0.01f, 0);
player.applyLinearImpulse(0, 40, pos.x, pos.y, true);
System.out.println("jump, " + player.getLinearVelocity());
}
}
// update platforms
for (int i = 0; i < platforms.size; i++) {
Platform platform = platforms.get(i);
platform.update(Math.max(1 / 30.0f, Gdx.graphics.getDeltaTime()));
}
// le step...
world.step(Gdx.graphics.getDeltaTime(), 4, 4);
// accum += Gdx.graphics.getDeltaTime();
// while(accum > TICK) {
// accum -= TICK;
// world.step(TICK, 4, 4);
// }
player.setAwake(true);
cam.project(point.set(pos.x, pos.y, 0));
batch.begin();
font.draw(batch, "friction: " + playerPhysicsFixture.getFriction() + "\ngrounded: " + grounded, point.x + 20, point.y);
batch.end();
}
private boolean isPlayerGrounded (float deltaTime) {
groundedPlatform = null;
Array<Contact> contactList = world.getContactList();
for (int i = 0; i < contactList.size; i++) {
Contact contact = contactList.get(i);
if (contact.isTouching()
&& (contact.getFixtureA() == playerSensorFixture || contact.getFixtureB() == playerSensorFixture)) {
Vector2 pos = player.getPosition();
WorldManifold manifold = contact.getWorldManifold();
boolean below = true;
for (int j = 0; j < manifold.getNumberOfContactPoints(); j++) {
below &= (manifold.getPoints()[j].y < pos.y - 1.5f);
}
if (below) {
if (contact.getFixtureA().getUserData() != null && contact.getFixtureA().getUserData().equals("p")) {
groundedPlatform = (Platform)contact.getFixtureA().getBody().getUserData();
}
if (contact.getFixtureB().getUserData() != null && contact.getFixtureB().getUserData().equals("p")) {
groundedPlatform = (Platform)contact.getFixtureB().getBody().getUserData();
}
return true;
}
return false;
}
}
return false;
}
@Override
public boolean keyDown (int keycode) {
if (keycode == Keys.W) jump = true;
return false;
}
@Override
public boolean keyUp (int keycode) {
if (keycode == Keys.W) jump = false;
return false;
}
Vector2 last = null;
Vector3 point = new Vector3();
@Override
public boolean touchDown (int x, int y, int pointerId, int button) {
cam.unproject(point.set(x, y, 0));
if (button == Input.Buttons.LEFT) {
if (last == null) {
last = new Vector2(point.x, point.y);
} else {
createEdge(BodyType.StaticBody, last.x, last.y, point.x, point.y, 0);
last.set(point.x, point.y);
}
} else {
last = null;
}
return false;
}
abstract class Platform {
abstract void update (float deltatime);
}
class CirclePlatform extends Platform {
Body platform;
public CirclePlatform (int x, int y, float radius, float da) {
platform = createCircle(BodyType.KinematicBody, radius, 1);
platform.setTransform(x, y, 0);
platform.getFixtureList().get(0).setUserData("p");
platform.setAngularVelocity(da);
platform.setUserData(this);
}
@Override
void update (float deltatime) {
}
}
class MovingPlatform extends Platform {
Body platform;
Vector2 pos = new Vector2();
Vector2 dir = new Vector2();
float dist = 0;
float maxDist = 0;
public MovingPlatform (float x, float y, float width, float height, float dx, float dy, float da, float maxDist) {
platform = createBox(BodyType.KinematicBody, width, height, 1);
pos.x = x;
pos.y = y;
dir.x = dx;
dir.y = dy;
this.maxDist = maxDist;
platform.setTransform(pos, 0);
platform.getFixtureList().get(0).setUserData("p");
platform.setAngularVelocity(da);
platform.setUserData(this);
}
public void update (float deltaTime) {
dist += dir.len() * deltaTime;
if (dist > maxDist) {
dir.scl(-1);
dist = 0;
}
platform.setLinearVelocity(dir);
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.physics.box2d.WorldManifold;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
public class Box2DCharacterControllerTest extends GdxTest implements ApplicationListener {
final static float MAX_VELOCITY = 14f;
boolean jump = false;
World world;
Body player;
Fixture playerPhysicsFixture;
Fixture playerSensorFixture;
OrthographicCamera cam;
Box2DDebugRenderer renderer;
Array<Platform> platforms = new Array<Platform>();
Platform groundedPlatform = null;
float stillTime = 0;
long lastGroundTime = 0;
SpriteBatch batch;
BitmapFont font;
float accum = 0;
float TICK = 1 / 60f;
@Override
public void create () {
world = new World(new Vector2(0, -40), true);
renderer = new Box2DDebugRenderer();
cam = new OrthographicCamera(28, 20);
createWorld();
Gdx.input.setInputProcessor(this);
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/lsans-15.fnt"), false);
}
@Override
public void dispose () {
world.dispose();
renderer.dispose();
batch.dispose();
font.dispose();
}
private void createWorld () {
float y1 = 1; // (float)Math.random() * 0.1f + 1;
float y2 = y1;
for (int i = 0; i < 50; i++) {
Body ground = createEdge(BodyType.StaticBody, -50 + i * 2, y1, -50 + i * 2 + 2, y2, 0);
y1 = y2;
y2 = 1; // (float)Math.random() + 1;
}
Body box = createBox(BodyType.StaticBody, 1, 1, 0);
box.setTransform(30, 3, 0);
box = createBox(BodyType.StaticBody, 1.2f, 1.2f, 0);
box.setTransform(5, 2.4f, 0);
player = createPlayer();
player.setTransform(-40.0f, 4.0f, 0);
player.setFixedRotation(true);
for (int i = 0; i < 20; i++) {
box = createBox(BodyType.DynamicBody, (float)Math.random(), (float)Math.random(), 3);
box.setTransform((float)Math.random() * 10f - (float)Math.random() * 10f, (float)Math.random() * 10 + 6,
(float)(Math.random() * 2 * Math.PI));
}
for (int i = 0; i < 20; i++) {
Body circle = createCircle(BodyType.DynamicBody, (float)Math.random() * 0.5f, 3);
circle.setTransform((float)Math.random() * 10f - (float)Math.random() * 10f, (float)Math.random() * 10 + 6,
(float)(Math.random() * 2 * Math.PI));
}
platforms.add(new CirclePlatform(-24, -5, 10, (float)Math.PI / 4));
platforms.add(new MovingPlatform(-2, 3, 2, 0.5f, 2, 0, (float)Math.PI / 10f, 4));
platforms.add(new MovingPlatform(17, 2, 5, 0.5f, 2, 0, 0, 5));
platforms.add(new MovingPlatform(-7, 5, 2, 0.5f, -2, 2, 0, 8));
// platforms.add(new MovingPlatform(40, 3, 20, 0.5f, 0, 2, 5));
}
Body createBox (BodyType type, float width, float height, float density) {
BodyDef def = new BodyDef();
def.type = type;
Body box = world.createBody(def);
PolygonShape poly = new PolygonShape();
poly.setAsBox(width, height);
box.createFixture(poly, density);
poly.dispose();
return box;
}
private Body createEdge (BodyType type, float x1, float y1, float x2, float y2, float density) {
BodyDef def = new BodyDef();
def.type = type;
Body box = world.createBody(def);
EdgeShape poly = new EdgeShape();
poly.set(new Vector2(0, 0), new Vector2(x2 - x1, y2 - y1));
box.createFixture(poly, density);
box.setTransform(x1, y1, 0);
poly.dispose();
return box;
}
Body createCircle (BodyType type, float radius, float density) {
BodyDef def = new BodyDef();
def.type = type;
Body box = world.createBody(def);
CircleShape poly = new CircleShape();
poly.setRadius(radius);
box.createFixture(poly, density);
poly.dispose();
return box;
}
private Body createPlayer () {
BodyDef def = new BodyDef();
def.type = BodyType.DynamicBody;
Body box = world.createBody(def);
PolygonShape poly = new PolygonShape();
poly.setAsBox(0.45f, 1.4f);
playerPhysicsFixture = box.createFixture(poly, 1);
poly.dispose();
CircleShape circle = new CircleShape();
circle.setRadius(0.45f);
circle.setPosition(new Vector2(0, -1.4f));
playerSensorFixture = box.createFixture(circle, 0);
circle.dispose();
box.setBullet(true);
return box;
}
@Override
public void resume () {
}
@Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
cam.position.set(player.getPosition().x, player.getPosition().y, 0);
cam.update();
renderer.render(world, cam.combined);
Vector2 vel = player.getLinearVelocity();
Vector2 pos = player.getPosition();
boolean grounded = isPlayerGrounded(Gdx.graphics.getDeltaTime());
if (grounded) {
lastGroundTime = TimeUtils.nanoTime();
} else {
if (TimeUtils.nanoTime() - lastGroundTime < 100000000) {
grounded = true;
}
}
// cap max velocity on x
if (Math.abs(vel.x) > MAX_VELOCITY) {
vel.x = Math.signum(vel.x) * MAX_VELOCITY;
player.setLinearVelocity(vel.x, vel.y);
}
// calculate stilltime & damp
if (!Gdx.input.isKeyPressed(Keys.A) && !Gdx.input.isKeyPressed(Keys.D)) {
stillTime += Gdx.graphics.getDeltaTime();
player.setLinearVelocity(vel.x * 0.9f, vel.y);
} else {
stillTime = 0;
}
// disable friction while jumping
if (!grounded) {
playerPhysicsFixture.setFriction(0f);
playerSensorFixture.setFriction(0f);
} else {
if (!Gdx.input.isKeyPressed(Keys.A) && !Gdx.input.isKeyPressed(Keys.D) && stillTime > 0.2) {
playerPhysicsFixture.setFriction(1000f);
playerSensorFixture.setFriction(1000f);
} else {
playerPhysicsFixture.setFriction(0.2f);
playerSensorFixture.setFriction(0.2f);
}
// dampen sudden changes in x/y of a MovingPlatform a little bit, otherwise
// character hops :)
if (groundedPlatform != null && groundedPlatform instanceof MovingPlatform
&& ((MovingPlatform)groundedPlatform).dist == 0) {
player.applyLinearImpulse(0, -24, pos.x, pos.y, true);
}
}
// since Box2D 2.2 we need to reset the friction of any existing contacts
Array<Contact> contacts = world.getContactList();
for (int i = 0; i < world.getContactCount(); i++) {
Contact contact = contacts.get(i);
contact.resetFriction();
}
// apply left impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Keys.A) && vel.x > -MAX_VELOCITY) {
player.applyLinearImpulse(-2f, 0, pos.x, pos.y, true);
}
// apply right impulse, but only if max velocity is not reached yet
if (Gdx.input.isKeyPressed(Keys.D) && vel.x < MAX_VELOCITY) {
player.applyLinearImpulse(2f, 0, pos.x, pos.y, true);
}
// jump, but only when grounded
if (jump) {
jump = false;
if (grounded) {
player.setLinearVelocity(vel.x, 0);
System.out.println("jump before: " + player.getLinearVelocity());
player.setTransform(pos.x, pos.y + 0.01f, 0);
player.applyLinearImpulse(0, 40, pos.x, pos.y, true);
System.out.println("jump, " + player.getLinearVelocity());
}
}
// update platforms
for (int i = 0; i < platforms.size; i++) {
Platform platform = platforms.get(i);
platform.update(Math.max(1 / 30.0f, Gdx.graphics.getDeltaTime()));
}
// le step...
world.step(Gdx.graphics.getDeltaTime(), 4, 4);
// accum += Gdx.graphics.getDeltaTime();
// while(accum > TICK) {
// accum -= TICK;
// world.step(TICK, 4, 4);
// }
player.setAwake(true);
cam.project(point.set(pos.x, pos.y, 0));
batch.begin();
font.draw(batch, "friction: " + playerPhysicsFixture.getFriction() + "\ngrounded: " + grounded, point.x + 20, point.y);
batch.end();
}
private boolean isPlayerGrounded (float deltaTime) {
groundedPlatform = null;
Array<Contact> contactList = world.getContactList();
for (int i = 0; i < contactList.size; i++) {
Contact contact = contactList.get(i);
if (contact.isTouching()
&& (contact.getFixtureA() == playerSensorFixture || contact.getFixtureB() == playerSensorFixture)) {
Vector2 pos = player.getPosition();
WorldManifold manifold = contact.getWorldManifold();
boolean below = true;
for (int j = 0; j < manifold.getNumberOfContactPoints(); j++) {
below &= (manifold.getPoints()[j].y < pos.y - 1.5f);
}
if (below) {
if (contact.getFixtureA().getUserData() != null && contact.getFixtureA().getUserData().equals("p")) {
groundedPlatform = (Platform)contact.getFixtureA().getBody().getUserData();
}
if (contact.getFixtureB().getUserData() != null && contact.getFixtureB().getUserData().equals("p")) {
groundedPlatform = (Platform)contact.getFixtureB().getBody().getUserData();
}
return true;
}
return false;
}
}
return false;
}
@Override
public boolean keyDown (int keycode) {
if (keycode == Keys.W) jump = true;
return false;
}
@Override
public boolean keyUp (int keycode) {
if (keycode == Keys.W) jump = false;
return false;
}
Vector2 last = null;
Vector3 point = new Vector3();
@Override
public boolean touchDown (int x, int y, int pointerId, int button) {
cam.unproject(point.set(x, y, 0));
if (button == Input.Buttons.LEFT) {
if (last == null) {
last = new Vector2(point.x, point.y);
} else {
createEdge(BodyType.StaticBody, last.x, last.y, point.x, point.y, 0);
last.set(point.x, point.y);
}
} else {
last = null;
}
return false;
}
abstract class Platform {
abstract void update (float deltatime);
}
class CirclePlatform extends Platform {
Body platform;
public CirclePlatform (int x, int y, float radius, float da) {
platform = createCircle(BodyType.KinematicBody, radius, 1);
platform.setTransform(x, y, 0);
platform.getFixtureList().get(0).setUserData("p");
platform.setAngularVelocity(da);
platform.setUserData(this);
}
@Override
void update (float deltatime) {
}
}
class MovingPlatform extends Platform {
Body platform;
Vector2 pos = new Vector2();
Vector2 dir = new Vector2();
float dist = 0;
float maxDist = 0;
public MovingPlatform (float x, float y, float width, float height, float dx, float dy, float da, float maxDist) {
platform = createBox(BodyType.KinematicBody, width, height, 1);
pos.x = x;
pos.y = y;
dir.x = dx;
dir.y = dy;
this.maxDist = maxDist;
platform.setTransform(pos, 0);
platform.getFixtureList().get(0).setUserData("p");
platform.setAngularVelocity(da);
platform.setUserData(this);
}
public void update (float deltaTime) {
dist += dir.len() * deltaTime;
if (dist > maxDist) {
dir.scl(-1);
dist = 0;
}
platform.setLinearVelocity(dir);
}
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btPositionAndRadius.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btPositionAndRadius extends BulletBase {
private long swigCPtr;
protected btPositionAndRadius (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btPositionAndRadius, normally you should not need this constructor it's intended for low-level usage. */
public btPositionAndRadius (long cPtr, boolean cMemoryOwn) {
this("btPositionAndRadius", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btPositionAndRadius obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btPositionAndRadius(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setPos (btVector3FloatData value) {
CollisionJNI.btPositionAndRadius_pos_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getPos () {
long cPtr = CollisionJNI.btPositionAndRadius_pos_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setRadius (float value) {
CollisionJNI.btPositionAndRadius_radius_set(swigCPtr, this, value);
}
public float getRadius () {
return CollisionJNI.btPositionAndRadius_radius_get(swigCPtr, this);
}
public btPositionAndRadius () {
this(CollisionJNI.new_btPositionAndRadius(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btPositionAndRadius extends BulletBase {
private long swigCPtr;
protected btPositionAndRadius (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btPositionAndRadius, normally you should not need this constructor it's intended for low-level usage. */
public btPositionAndRadius (long cPtr, boolean cMemoryOwn) {
this("btPositionAndRadius", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btPositionAndRadius obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btPositionAndRadius(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setPos (btVector3FloatData value) {
CollisionJNI.btPositionAndRadius_pos_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getPos () {
long cPtr = CollisionJNI.btPositionAndRadius_pos_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setRadius (float value) {
CollisionJNI.btPositionAndRadius_radius_set(swigCPtr, this, value);
}
public float getRadius () {
return CollisionJNI.btPositionAndRadius_radius_get(swigCPtr, this);
}
public btPositionAndRadius () {
this(CollisionJNI.new_btPositionAndRadius(), true);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/java/nio/DirectReadOnlyShortBufferAdapter.java | /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio;
import com.google.gwt.typedarrays.shared.ArrayBufferView;
import com.google.gwt.typedarrays.shared.Int16Array;
import com.google.gwt.typedarrays.shared.TypedArrays;
/** This class wraps a byte buffer to be a short buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the
* adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position
* and limit.</li>
* </ul>
* </p>
*/
final class DirectReadOnlyShortBufferAdapter extends ShortBuffer implements HasArrayBufferView {
static ShortBuffer wrap (DirectByteBuffer byteBuffer) {
return new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.slice());
}
private final DirectByteBuffer byteBuffer;
private final Int16Array shortArray;
DirectReadOnlyShortBufferAdapter (DirectByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 1));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
this.shortArray = TypedArrays.createInt16Array(byteBuffer.byteArray.buffer(), byteBuffer.byteArray.byteOffset(), capacity);
}
@Override
public ShortBuffer asReadOnlyBuffer () {
DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter(byteBuffer);
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public ShortBuffer compact () {
throw new ReadOnlyBufferException();
}
@Override
public ShortBuffer duplicate () {
DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public short get () {
// if (position == limit) {
// throw new BufferUnderflowException();
// }
return (short)shortArray.get(position++);
}
@Override
public short get (int index) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
return (short)shortArray.get(index);
}
@Override
public boolean isDirect () {
return true;
}
@Override
public boolean isReadOnly () {
return true;
}
@Override
public ByteOrder order () {
return byteBuffer.order();
}
@Override
protected short[] protectedArray () {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset () {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray () {
return false;
}
@Override
public ShortBuffer put (short c) {
throw new ReadOnlyBufferException();
}
@Override
public ShortBuffer put (int index, short c) {
throw new ReadOnlyBufferException();
}
@Override
public ShortBuffer slice () {
byteBuffer.limit(limit << 1);
byteBuffer.position(position << 1);
ShortBuffer result = new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.slice());
byteBuffer.clear();
return result;
}
public ArrayBufferView getTypedArray () {
return shortArray;
}
public int getElementSize () {
return 2;
}
}
| /* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.nio;
import com.google.gwt.typedarrays.shared.ArrayBufferView;
import com.google.gwt.typedarrays.shared.Int16Array;
import com.google.gwt.typedarrays.shared.TypedArrays;
/** This class wraps a byte buffer to be a short buffer.
* <p>
* Implementation notice:
* <ul>
* <li>After a byte buffer instance is wrapped, it becomes privately owned by the adapter. It must NOT be accessed outside the
* adapter any more.</li>
* <li>The byte buffer's position and limit are NOT linked with the adapter. The adapter extends Buffer, thus has its own position
* and limit.</li>
* </ul>
* </p>
*/
final class DirectReadOnlyShortBufferAdapter extends ShortBuffer implements HasArrayBufferView {
static ShortBuffer wrap (DirectByteBuffer byteBuffer) {
return new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.slice());
}
private final DirectByteBuffer byteBuffer;
private final Int16Array shortArray;
DirectReadOnlyShortBufferAdapter (DirectByteBuffer byteBuffer) {
super((byteBuffer.capacity() >> 1));
this.byteBuffer = byteBuffer;
this.byteBuffer.clear();
this.shortArray = TypedArrays.createInt16Array(byteBuffer.byteArray.buffer(), byteBuffer.byteArray.byteOffset(), capacity);
}
@Override
public ShortBuffer asReadOnlyBuffer () {
DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter(byteBuffer);
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public ShortBuffer compact () {
throw new ReadOnlyBufferException();
}
@Override
public ShortBuffer duplicate () {
DirectReadOnlyShortBufferAdapter buf = new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.duplicate());
buf.limit = limit;
buf.position = position;
buf.mark = mark;
return buf;
}
@Override
public short get () {
// if (position == limit) {
// throw new BufferUnderflowException();
// }
return (short)shortArray.get(position++);
}
@Override
public short get (int index) {
// if (index < 0 || index >= limit) {
// throw new IndexOutOfBoundsException();
// }
return (short)shortArray.get(index);
}
@Override
public boolean isDirect () {
return true;
}
@Override
public boolean isReadOnly () {
return true;
}
@Override
public ByteOrder order () {
return byteBuffer.order();
}
@Override
protected short[] protectedArray () {
throw new UnsupportedOperationException();
}
@Override
protected int protectedArrayOffset () {
throw new UnsupportedOperationException();
}
@Override
protected boolean protectedHasArray () {
return false;
}
@Override
public ShortBuffer put (short c) {
throw new ReadOnlyBufferException();
}
@Override
public ShortBuffer put (int index, short c) {
throw new ReadOnlyBufferException();
}
@Override
public ShortBuffer slice () {
byteBuffer.limit(limit << 1);
byteBuffer.position(position << 1);
ShortBuffer result = new DirectReadOnlyShortBufferAdapter((DirectByteBuffer)byteBuffer.slice());
byteBuffer.clear();
return result;
}
public ArrayBufferView getTypedArray () {
return shortArray;
}
public int getElementSize () {
return 2;
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btSphereSphereCollisionAlgorithm.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btSphereSphereCollisionAlgorithm extends btActivatingCollisionAlgorithm {
private long swigCPtr;
protected btSphereSphereCollisionAlgorithm (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSphereSphereCollisionAlgorithm_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSphereSphereCollisionAlgorithm, normally you should not need this constructor it's intended for low-level
* usage. */
public btSphereSphereCollisionAlgorithm (long cPtr, boolean cMemoryOwn) {
this("btSphereSphereCollisionAlgorithm", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSphereSphereCollisionAlgorithm_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSphereSphereCollisionAlgorithm obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSphereSphereCollisionAlgorithm(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btSphereSphereCollisionAlgorithm (btPersistentManifold mf, btCollisionAlgorithmConstructionInfo ci,
btCollisionObjectWrapper col0Wrap, btCollisionObjectWrapper col1Wrap) {
this(CollisionJNI.new_btSphereSphereCollisionAlgorithm__SWIG_0(btPersistentManifold.getCPtr(mf), mf,
btCollisionAlgorithmConstructionInfo.getCPtr(ci), ci, btCollisionObjectWrapper.getCPtr(col0Wrap), col0Wrap,
btCollisionObjectWrapper.getCPtr(col1Wrap), col1Wrap), true);
}
public btSphereSphereCollisionAlgorithm (btCollisionAlgorithmConstructionInfo ci) {
this(CollisionJNI.new_btSphereSphereCollisionAlgorithm__SWIG_1(btCollisionAlgorithmConstructionInfo.getCPtr(ci), ci), true);
}
static public class CreateFunc extends btCollisionAlgorithmCreateFunc {
private long swigCPtr;
protected CreateFunc (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSphereSphereCollisionAlgorithm_CreateFunc_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new CreateFunc, normally you should not need this constructor it's intended for low-level usage. */
public CreateFunc (long cPtr, boolean cMemoryOwn) {
this("CreateFunc", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSphereSphereCollisionAlgorithm_CreateFunc_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (CreateFunc obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSphereSphereCollisionAlgorithm_CreateFunc(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public CreateFunc () {
this(CollisionJNI.new_btSphereSphereCollisionAlgorithm_CreateFunc(), true);
}
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btSphereSphereCollisionAlgorithm extends btActivatingCollisionAlgorithm {
private long swigCPtr;
protected btSphereSphereCollisionAlgorithm (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSphereSphereCollisionAlgorithm_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSphereSphereCollisionAlgorithm, normally you should not need this constructor it's intended for low-level
* usage. */
public btSphereSphereCollisionAlgorithm (long cPtr, boolean cMemoryOwn) {
this("btSphereSphereCollisionAlgorithm", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSphereSphereCollisionAlgorithm_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSphereSphereCollisionAlgorithm obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSphereSphereCollisionAlgorithm(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btSphereSphereCollisionAlgorithm (btPersistentManifold mf, btCollisionAlgorithmConstructionInfo ci,
btCollisionObjectWrapper col0Wrap, btCollisionObjectWrapper col1Wrap) {
this(CollisionJNI.new_btSphereSphereCollisionAlgorithm__SWIG_0(btPersistentManifold.getCPtr(mf), mf,
btCollisionAlgorithmConstructionInfo.getCPtr(ci), ci, btCollisionObjectWrapper.getCPtr(col0Wrap), col0Wrap,
btCollisionObjectWrapper.getCPtr(col1Wrap), col1Wrap), true);
}
public btSphereSphereCollisionAlgorithm (btCollisionAlgorithmConstructionInfo ci) {
this(CollisionJNI.new_btSphereSphereCollisionAlgorithm__SWIG_1(btCollisionAlgorithmConstructionInfo.getCPtr(ci), ci), true);
}
static public class CreateFunc extends btCollisionAlgorithmCreateFunc {
private long swigCPtr;
protected CreateFunc (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSphereSphereCollisionAlgorithm_CreateFunc_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new CreateFunc, normally you should not need this constructor it's intended for low-level usage. */
public CreateFunc (long cPtr, boolean cMemoryOwn) {
this("CreateFunc", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSphereSphereCollisionAlgorithm_CreateFunc_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (CreateFunc obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSphereSphereCollisionAlgorithm_CreateFunc(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public CreateFunc () {
this(CollisionJNI.new_btSphereSphereCollisionAlgorithm_CreateFunc(), true);
}
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btQuantizedBvhFloatData.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btQuantizedBvhFloatData extends BulletBase {
private long swigCPtr;
protected btQuantizedBvhFloatData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btQuantizedBvhFloatData, normally you should not need this constructor it's intended for low-level
* usage. */
public btQuantizedBvhFloatData (long cPtr, boolean cMemoryOwn) {
this("btQuantizedBvhFloatData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btQuantizedBvhFloatData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btQuantizedBvhFloatData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setBvhAabbMin (btVector3FloatData value) {
CollisionJNI.btQuantizedBvhFloatData_bvhAabbMin_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getBvhAabbMin () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_bvhAabbMin_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setBvhAabbMax (btVector3FloatData value) {
CollisionJNI.btQuantizedBvhFloatData_bvhAabbMax_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getBvhAabbMax () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_bvhAabbMax_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setBvhQuantization (btVector3FloatData value) {
CollisionJNI.btQuantizedBvhFloatData_bvhQuantization_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getBvhQuantization () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_bvhQuantization_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setCurNodeIndex (int value) {
CollisionJNI.btQuantizedBvhFloatData_curNodeIndex_set(swigCPtr, this, value);
}
public int getCurNodeIndex () {
return CollisionJNI.btQuantizedBvhFloatData_curNodeIndex_get(swigCPtr, this);
}
public void setUseQuantization (int value) {
CollisionJNI.btQuantizedBvhFloatData_useQuantization_set(swigCPtr, this, value);
}
public int getUseQuantization () {
return CollisionJNI.btQuantizedBvhFloatData_useQuantization_get(swigCPtr, this);
}
public void setNumContiguousLeafNodes (int value) {
CollisionJNI.btQuantizedBvhFloatData_numContiguousLeafNodes_set(swigCPtr, this, value);
}
public int getNumContiguousLeafNodes () {
return CollisionJNI.btQuantizedBvhFloatData_numContiguousLeafNodes_get(swigCPtr, this);
}
public void setNumQuantizedContiguousNodes (int value) {
CollisionJNI.btQuantizedBvhFloatData_numQuantizedContiguousNodes_set(swigCPtr, this, value);
}
public int getNumQuantizedContiguousNodes () {
return CollisionJNI.btQuantizedBvhFloatData_numQuantizedContiguousNodes_get(swigCPtr, this);
}
public void setContiguousNodesPtr (btOptimizedBvhNodeFloatData value) {
CollisionJNI.btQuantizedBvhFloatData_contiguousNodesPtr_set(swigCPtr, this, btOptimizedBvhNodeFloatData.getCPtr(value),
value);
}
public btOptimizedBvhNodeFloatData getContiguousNodesPtr () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_contiguousNodesPtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btOptimizedBvhNodeFloatData(cPtr, false);
}
public void setQuantizedContiguousNodesPtr (btQuantizedBvhNodeData value) {
CollisionJNI.btQuantizedBvhFloatData_quantizedContiguousNodesPtr_set(swigCPtr, this, btQuantizedBvhNodeData.getCPtr(value),
value);
}
public btQuantizedBvhNodeData getQuantizedContiguousNodesPtr () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_quantizedContiguousNodesPtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btQuantizedBvhNodeData(cPtr, false);
}
public void setSubTreeInfoPtr (btBvhSubtreeInfoData value) {
CollisionJNI.btQuantizedBvhFloatData_subTreeInfoPtr_set(swigCPtr, this, btBvhSubtreeInfoData.getCPtr(value), value);
}
public btBvhSubtreeInfoData getSubTreeInfoPtr () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_subTreeInfoPtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btBvhSubtreeInfoData(cPtr, false);
}
public void setTraversalMode (int value) {
CollisionJNI.btQuantizedBvhFloatData_traversalMode_set(swigCPtr, this, value);
}
public int getTraversalMode () {
return CollisionJNI.btQuantizedBvhFloatData_traversalMode_get(swigCPtr, this);
}
public void setNumSubtreeHeaders (int value) {
CollisionJNI.btQuantizedBvhFloatData_numSubtreeHeaders_set(swigCPtr, this, value);
}
public int getNumSubtreeHeaders () {
return CollisionJNI.btQuantizedBvhFloatData_numSubtreeHeaders_get(swigCPtr, this);
}
public btQuantizedBvhFloatData () {
this(CollisionJNI.new_btQuantizedBvhFloatData(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btQuantizedBvhFloatData extends BulletBase {
private long swigCPtr;
protected btQuantizedBvhFloatData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btQuantizedBvhFloatData, normally you should not need this constructor it's intended for low-level
* usage. */
public btQuantizedBvhFloatData (long cPtr, boolean cMemoryOwn) {
this("btQuantizedBvhFloatData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btQuantizedBvhFloatData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btQuantizedBvhFloatData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setBvhAabbMin (btVector3FloatData value) {
CollisionJNI.btQuantizedBvhFloatData_bvhAabbMin_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getBvhAabbMin () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_bvhAabbMin_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setBvhAabbMax (btVector3FloatData value) {
CollisionJNI.btQuantizedBvhFloatData_bvhAabbMax_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getBvhAabbMax () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_bvhAabbMax_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setBvhQuantization (btVector3FloatData value) {
CollisionJNI.btQuantizedBvhFloatData_bvhQuantization_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getBvhQuantization () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_bvhQuantization_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setCurNodeIndex (int value) {
CollisionJNI.btQuantizedBvhFloatData_curNodeIndex_set(swigCPtr, this, value);
}
public int getCurNodeIndex () {
return CollisionJNI.btQuantizedBvhFloatData_curNodeIndex_get(swigCPtr, this);
}
public void setUseQuantization (int value) {
CollisionJNI.btQuantizedBvhFloatData_useQuantization_set(swigCPtr, this, value);
}
public int getUseQuantization () {
return CollisionJNI.btQuantizedBvhFloatData_useQuantization_get(swigCPtr, this);
}
public void setNumContiguousLeafNodes (int value) {
CollisionJNI.btQuantizedBvhFloatData_numContiguousLeafNodes_set(swigCPtr, this, value);
}
public int getNumContiguousLeafNodes () {
return CollisionJNI.btQuantizedBvhFloatData_numContiguousLeafNodes_get(swigCPtr, this);
}
public void setNumQuantizedContiguousNodes (int value) {
CollisionJNI.btQuantizedBvhFloatData_numQuantizedContiguousNodes_set(swigCPtr, this, value);
}
public int getNumQuantizedContiguousNodes () {
return CollisionJNI.btQuantizedBvhFloatData_numQuantizedContiguousNodes_get(swigCPtr, this);
}
public void setContiguousNodesPtr (btOptimizedBvhNodeFloatData value) {
CollisionJNI.btQuantizedBvhFloatData_contiguousNodesPtr_set(swigCPtr, this, btOptimizedBvhNodeFloatData.getCPtr(value),
value);
}
public btOptimizedBvhNodeFloatData getContiguousNodesPtr () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_contiguousNodesPtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btOptimizedBvhNodeFloatData(cPtr, false);
}
public void setQuantizedContiguousNodesPtr (btQuantizedBvhNodeData value) {
CollisionJNI.btQuantizedBvhFloatData_quantizedContiguousNodesPtr_set(swigCPtr, this, btQuantizedBvhNodeData.getCPtr(value),
value);
}
public btQuantizedBvhNodeData getQuantizedContiguousNodesPtr () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_quantizedContiguousNodesPtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btQuantizedBvhNodeData(cPtr, false);
}
public void setSubTreeInfoPtr (btBvhSubtreeInfoData value) {
CollisionJNI.btQuantizedBvhFloatData_subTreeInfoPtr_set(swigCPtr, this, btBvhSubtreeInfoData.getCPtr(value), value);
}
public btBvhSubtreeInfoData getSubTreeInfoPtr () {
long cPtr = CollisionJNI.btQuantizedBvhFloatData_subTreeInfoPtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btBvhSubtreeInfoData(cPtr, false);
}
public void setTraversalMode (int value) {
CollisionJNI.btQuantizedBvhFloatData_traversalMode_set(swigCPtr, this, value);
}
public int getTraversalMode () {
return CollisionJNI.btQuantizedBvhFloatData_traversalMode_get(swigCPtr, this);
}
public void setNumSubtreeHeaders (int value) {
CollisionJNI.btQuantizedBvhFloatData_numSubtreeHeaders_set(swigCPtr, this, value);
}
public int getNumSubtreeHeaders () {
return CollisionJNI.btQuantizedBvhFloatData_numSubtreeHeaders_get(swigCPtr, this);
}
public btQuantizedBvhFloatData () {
this(CollisionJNI.new_btQuantizedBvhFloatData(), true);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/linearmath/com/badlogic/gdx/physics/bullet/linearmath/HullLibrary.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.linearmath;
import com.badlogic.gdx.physics.bullet.BulletBase;
public class HullLibrary extends BulletBase {
private long swigCPtr;
protected HullLibrary (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new HullLibrary, normally you should not need this constructor it's intended for low-level usage. */
public HullLibrary (long cPtr, boolean cMemoryOwn) {
this("HullLibrary", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (HullLibrary obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
LinearMathJNI.delete_HullLibrary(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setVertexIndexMapping (SWIGTYPE_p_btAlignedObjectArrayT_int_t value) {
LinearMathJNI.HullLibrary_vertexIndexMapping_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_int_t.getCPtr(value));
}
public SWIGTYPE_p_btAlignedObjectArrayT_int_t getVertexIndexMapping () {
long cPtr = LinearMathJNI.HullLibrary_vertexIndexMapping_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_int_t(cPtr, false);
}
public int CreateConvexHull (HullDesc desc, HullResult result) {
return LinearMathJNI.HullLibrary_CreateConvexHull(swigCPtr, this, HullDesc.getCPtr(desc), desc, HullResult.getCPtr(result),
result);
}
public int ReleaseResult (HullResult result) {
return LinearMathJNI.HullLibrary_ReleaseResult(swigCPtr, this, HullResult.getCPtr(result), result);
}
public HullLibrary () {
this(LinearMathJNI.new_HullLibrary(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.linearmath;
import com.badlogic.gdx.physics.bullet.BulletBase;
public class HullLibrary extends BulletBase {
private long swigCPtr;
protected HullLibrary (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new HullLibrary, normally you should not need this constructor it's intended for low-level usage. */
public HullLibrary (long cPtr, boolean cMemoryOwn) {
this("HullLibrary", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (HullLibrary obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
LinearMathJNI.delete_HullLibrary(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setVertexIndexMapping (SWIGTYPE_p_btAlignedObjectArrayT_int_t value) {
LinearMathJNI.HullLibrary_vertexIndexMapping_set(swigCPtr, this, SWIGTYPE_p_btAlignedObjectArrayT_int_t.getCPtr(value));
}
public SWIGTYPE_p_btAlignedObjectArrayT_int_t getVertexIndexMapping () {
long cPtr = LinearMathJNI.HullLibrary_vertexIndexMapping_get(swigCPtr, this);
return (cPtr == 0) ? null : new SWIGTYPE_p_btAlignedObjectArrayT_int_t(cPtr, false);
}
public int CreateConvexHull (HullDesc desc, HullResult result) {
return LinearMathJNI.HullLibrary_CreateConvexHull(swigCPtr, this, HullDesc.getCPtr(desc), desc, HullResult.getCPtr(result),
result);
}
public int ReleaseResult (HullResult result) {
return LinearMathJNI.HullLibrary_ReleaseResult(swigCPtr, this, HullResult.getCPtr(result), result);
}
public HullLibrary () {
this(LinearMathJNI.new_HullLibrary(), true);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/dynamics/com/badlogic/gdx/physics/bullet/dynamics/btMultiBodyLinkCollider.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btMultiBodyLinkCollider extends btCollisionObject {
private long swigCPtr;
protected btMultiBodyLinkCollider (final String className, long cPtr, boolean cMemoryOwn) {
super(className, DynamicsJNI.btMultiBodyLinkCollider_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btMultiBodyLinkCollider, normally you should not need this constructor it's intended for low-level
* usage. */
public btMultiBodyLinkCollider (long cPtr, boolean cMemoryOwn) {
this("btMultiBodyLinkCollider", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(DynamicsJNI.btMultiBodyLinkCollider_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btMultiBodyLinkCollider obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btMultiBodyLinkCollider(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setMultiBody (btMultiBody value) {
DynamicsJNI.btMultiBodyLinkCollider_multiBody_set(swigCPtr, this, btMultiBody.getCPtr(value), value);
}
public btMultiBody getMultiBody () {
long cPtr = DynamicsJNI.btMultiBodyLinkCollider_multiBody_get(swigCPtr, this);
return (cPtr == 0) ? null : new btMultiBody(cPtr, false);
}
public void setLink (int value) {
DynamicsJNI.btMultiBodyLinkCollider_link_set(swigCPtr, this, value);
}
public int getLink () {
return DynamicsJNI.btMultiBodyLinkCollider_link_get(swigCPtr, this);
}
public btMultiBodyLinkCollider (btMultiBody multiBody, int link) {
this(DynamicsJNI.new_btMultiBodyLinkCollider(btMultiBody.getCPtr(multiBody), multiBody, link), true);
}
public static btMultiBodyLinkCollider upcast (btCollisionObject colObj) {
long cPtr = DynamicsJNI.btMultiBodyLinkCollider_upcast(btCollisionObject.getCPtr(colObj), colObj);
return (cPtr == 0) ? null : new btMultiBodyLinkCollider(cPtr, false);
}
public static btMultiBodyLinkCollider upcastConstBtCollisionObject (btCollisionObject colObj) {
long cPtr = DynamicsJNI.btMultiBodyLinkCollider_upcastConstBtCollisionObject(btCollisionObject.getCPtr(colObj), colObj);
return (cPtr == 0) ? null : new btMultiBodyLinkCollider(cPtr, false);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btMultiBodyLinkCollider extends btCollisionObject {
private long swigCPtr;
protected btMultiBodyLinkCollider (final String className, long cPtr, boolean cMemoryOwn) {
super(className, DynamicsJNI.btMultiBodyLinkCollider_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btMultiBodyLinkCollider, normally you should not need this constructor it's intended for low-level
* usage. */
public btMultiBodyLinkCollider (long cPtr, boolean cMemoryOwn) {
this("btMultiBodyLinkCollider", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(DynamicsJNI.btMultiBodyLinkCollider_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btMultiBodyLinkCollider obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btMultiBodyLinkCollider(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setMultiBody (btMultiBody value) {
DynamicsJNI.btMultiBodyLinkCollider_multiBody_set(swigCPtr, this, btMultiBody.getCPtr(value), value);
}
public btMultiBody getMultiBody () {
long cPtr = DynamicsJNI.btMultiBodyLinkCollider_multiBody_get(swigCPtr, this);
return (cPtr == 0) ? null : new btMultiBody(cPtr, false);
}
public void setLink (int value) {
DynamicsJNI.btMultiBodyLinkCollider_link_set(swigCPtr, this, value);
}
public int getLink () {
return DynamicsJNI.btMultiBodyLinkCollider_link_get(swigCPtr, this);
}
public btMultiBodyLinkCollider (btMultiBody multiBody, int link) {
this(DynamicsJNI.new_btMultiBodyLinkCollider(btMultiBody.getCPtr(multiBody), multiBody, link), true);
}
public static btMultiBodyLinkCollider upcast (btCollisionObject colObj) {
long cPtr = DynamicsJNI.btMultiBodyLinkCollider_upcast(btCollisionObject.getCPtr(colObj), colObj);
return (cPtr == 0) ? null : new btMultiBodyLinkCollider(cPtr, false);
}
public static btMultiBodyLinkCollider upcastConstBtCollisionObject (btCollisionObject colObj) {
long cPtr = DynamicsJNI.btMultiBodyLinkCollider_upcastConstBtCollisionObject(btCollisionObject.getCPtr(colObj), colObj);
return (cPtr == 0) ? null : new btMultiBodyLinkCollider(cPtr, false);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./gdx/src/com/badlogic/gdx/math/Ellipse.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.math;
import java.io.Serializable;
import com.badlogic.gdx.utils.NumberUtils;
/** A convenient 2D ellipse class, based on the circle class
* @author tonyp7 */
public class Ellipse implements Serializable, Shape2D {
public float x, y;
public float width, height;
private static final long serialVersionUID = 7381533206532032099L;
/** Construct a new ellipse with all values set to zero */
public Ellipse () {
}
/** Copy constructor
*
* @param ellipse Ellipse to construct a copy of. */
public Ellipse (Ellipse ellipse) {
this.x = ellipse.x;
this.y = ellipse.y;
this.width = ellipse.width;
this.height = ellipse.height;
}
/** Constructs a new ellipse
*
* @param x X coordinate
* @param y Y coordinate
* @param width the width of the ellipse
* @param height the height of the ellipse */
public Ellipse (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** Constructs a new ellipse
*
* @param position Position vector
* @param width the width of the ellipse
* @param height the height of the ellipse */
public Ellipse (Vector2 position, float width, float height) {
this.x = position.x;
this.y = position.y;
this.width = width;
this.height = height;
}
/** Constructs a new ellipse
*
* @param position Position vector
* @param size Size vector */
public Ellipse (Vector2 position, Vector2 size) {
this.x = position.x;
this.y = position.y;
this.width = size.x;
this.height = size.y;
}
/** Constructs a new {@link Ellipse} from the position and radius of a {@link Circle} (since circles are special cases of
* ellipses).
* @param circle The circle to take the values of */
public Ellipse (Circle circle) {
this.x = circle.x;
this.y = circle.y;
this.width = circle.radius * 2f;
this.height = circle.radius * 2f;
}
/** Checks whether or not this ellipse contains the given point.
*
* @param x X coordinate
* @param y Y coordinate
*
* @return true if this ellipse contains the given point; false otherwise. */
public boolean contains (float x, float y) {
x = x - this.x;
y = y - this.y;
return (x * x) / (width * 0.5f * width * 0.5f) + (y * y) / (height * 0.5f * height * 0.5f) <= 1.0f;
}
/** Checks whether or not this ellipse contains the given point.
*
* @param point Position vector
*
* @return true if this ellipse contains the given point; false otherwise. */
public boolean contains (Vector2 point) {
return contains(point.x, point.y);
}
/** Sets a new position and size for this ellipse.
*
* @param x X coordinate
* @param y Y coordinate
* @param width the width of the ellipse
* @param height the height of the ellipse */
public void set (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** Sets a new position and size for this ellipse based upon another ellipse.
*
* @param ellipse The ellipse to copy the position and size of. */
public void set (Ellipse ellipse) {
x = ellipse.x;
y = ellipse.y;
width = ellipse.width;
height = ellipse.height;
}
public void set (Circle circle) {
this.x = circle.x;
this.y = circle.y;
this.width = circle.radius * 2f;
this.height = circle.radius * 2f;
}
public void set (Vector2 position, Vector2 size) {
this.x = position.x;
this.y = position.y;
this.width = size.x;
this.height = size.y;
}
/** Sets the x and y-coordinates of ellipse center from a {@link Vector2}.
* @param position The position vector
* @return this ellipse for chaining */
public Ellipse setPosition (Vector2 position) {
this.x = position.x;
this.y = position.y;
return this;
}
/** Sets the x and y-coordinates of ellipse center
* @param x The x-coordinate
* @param y The y-coordinate
* @return this ellipse for chaining */
public Ellipse setPosition (float x, float y) {
this.x = x;
this.y = y;
return this;
}
/** Sets the width and height of this ellipse
* @param width The width
* @param height The height
* @return this ellipse for chaining */
public Ellipse setSize (float width, float height) {
this.width = width;
this.height = height;
return this;
}
/** @return The area of this {@link Ellipse} as {@link MathUtils#PI} * {@link Ellipse#width} * {@link Ellipse#height} */
public float area () {
return MathUtils.PI * (this.width * this.height) / 4;
}
/** Approximates the circumference of this {@link Ellipse}. Oddly enough, the circumference of an ellipse is actually difficult
* to compute exactly.
* @return The Ramanujan approximation to the circumference of an ellipse if one dimension is at least three times longer than
* the other, else the simpler approximation */
public float circumference () {
float a = this.width / 2;
float b = this.height / 2;
if (a * 3 > b || b * 3 > a) {
// If one dimension is three times as long as the other...
return (float)(MathUtils.PI * ((3 * (a + b)) - Math.sqrt((3 * a + b) * (a + 3 * b))));
} else {
// We can use the simpler approximation, then
return (float)(MathUtils.PI2 * Math.sqrt((a * a + b * b) / 2));
}
}
@Override
public boolean equals (Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
Ellipse e = (Ellipse)o;
return this.x == e.x && this.y == e.y && this.width == e.width && this.height == e.height;
}
@Override
public int hashCode () {
final int prime = 53;
int result = 1;
result = prime * result + NumberUtils.floatToRawIntBits(this.height);
result = prime * result + NumberUtils.floatToRawIntBits(this.width);
result = prime * result + NumberUtils.floatToRawIntBits(this.x);
result = prime * result + NumberUtils.floatToRawIntBits(this.y);
return result;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.math;
import java.io.Serializable;
import com.badlogic.gdx.utils.NumberUtils;
/** A convenient 2D ellipse class, based on the circle class
* @author tonyp7 */
public class Ellipse implements Serializable, Shape2D {
public float x, y;
public float width, height;
private static final long serialVersionUID = 7381533206532032099L;
/** Construct a new ellipse with all values set to zero */
public Ellipse () {
}
/** Copy constructor
*
* @param ellipse Ellipse to construct a copy of. */
public Ellipse (Ellipse ellipse) {
this.x = ellipse.x;
this.y = ellipse.y;
this.width = ellipse.width;
this.height = ellipse.height;
}
/** Constructs a new ellipse
*
* @param x X coordinate
* @param y Y coordinate
* @param width the width of the ellipse
* @param height the height of the ellipse */
public Ellipse (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** Constructs a new ellipse
*
* @param position Position vector
* @param width the width of the ellipse
* @param height the height of the ellipse */
public Ellipse (Vector2 position, float width, float height) {
this.x = position.x;
this.y = position.y;
this.width = width;
this.height = height;
}
/** Constructs a new ellipse
*
* @param position Position vector
* @param size Size vector */
public Ellipse (Vector2 position, Vector2 size) {
this.x = position.x;
this.y = position.y;
this.width = size.x;
this.height = size.y;
}
/** Constructs a new {@link Ellipse} from the position and radius of a {@link Circle} (since circles are special cases of
* ellipses).
* @param circle The circle to take the values of */
public Ellipse (Circle circle) {
this.x = circle.x;
this.y = circle.y;
this.width = circle.radius * 2f;
this.height = circle.radius * 2f;
}
/** Checks whether or not this ellipse contains the given point.
*
* @param x X coordinate
* @param y Y coordinate
*
* @return true if this ellipse contains the given point; false otherwise. */
public boolean contains (float x, float y) {
x = x - this.x;
y = y - this.y;
return (x * x) / (width * 0.5f * width * 0.5f) + (y * y) / (height * 0.5f * height * 0.5f) <= 1.0f;
}
/** Checks whether or not this ellipse contains the given point.
*
* @param point Position vector
*
* @return true if this ellipse contains the given point; false otherwise. */
public boolean contains (Vector2 point) {
return contains(point.x, point.y);
}
/** Sets a new position and size for this ellipse.
*
* @param x X coordinate
* @param y Y coordinate
* @param width the width of the ellipse
* @param height the height of the ellipse */
public void set (float x, float y, float width, float height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/** Sets a new position and size for this ellipse based upon another ellipse.
*
* @param ellipse The ellipse to copy the position and size of. */
public void set (Ellipse ellipse) {
x = ellipse.x;
y = ellipse.y;
width = ellipse.width;
height = ellipse.height;
}
public void set (Circle circle) {
this.x = circle.x;
this.y = circle.y;
this.width = circle.radius * 2f;
this.height = circle.radius * 2f;
}
public void set (Vector2 position, Vector2 size) {
this.x = position.x;
this.y = position.y;
this.width = size.x;
this.height = size.y;
}
/** Sets the x and y-coordinates of ellipse center from a {@link Vector2}.
* @param position The position vector
* @return this ellipse for chaining */
public Ellipse setPosition (Vector2 position) {
this.x = position.x;
this.y = position.y;
return this;
}
/** Sets the x and y-coordinates of ellipse center
* @param x The x-coordinate
* @param y The y-coordinate
* @return this ellipse for chaining */
public Ellipse setPosition (float x, float y) {
this.x = x;
this.y = y;
return this;
}
/** Sets the width and height of this ellipse
* @param width The width
* @param height The height
* @return this ellipse for chaining */
public Ellipse setSize (float width, float height) {
this.width = width;
this.height = height;
return this;
}
/** @return The area of this {@link Ellipse} as {@link MathUtils#PI} * {@link Ellipse#width} * {@link Ellipse#height} */
public float area () {
return MathUtils.PI * (this.width * this.height) / 4;
}
/** Approximates the circumference of this {@link Ellipse}. Oddly enough, the circumference of an ellipse is actually difficult
* to compute exactly.
* @return The Ramanujan approximation to the circumference of an ellipse if one dimension is at least three times longer than
* the other, else the simpler approximation */
public float circumference () {
float a = this.width / 2;
float b = this.height / 2;
if (a * 3 > b || b * 3 > a) {
// If one dimension is three times as long as the other...
return (float)(MathUtils.PI * ((3 * (a + b)) - Math.sqrt((3 * a + b) * (a + 3 * b))));
} else {
// We can use the simpler approximation, then
return (float)(MathUtils.PI2 * Math.sqrt((a * a + b * b) / 2));
}
}
@Override
public boolean equals (Object o) {
if (o == this) return true;
if (o == null || o.getClass() != this.getClass()) return false;
Ellipse e = (Ellipse)o;
return this.x == e.x && this.y == e.y && this.width == e.width && this.height == e.height;
}
@Override
public int hashCode () {
final int prime = 53;
int result = 1;
result = prime * result + NumberUtils.floatToRawIntBits(this.height);
result = prime * result + NumberUtils.floatToRawIntBits(this.width);
result = prime * result + NumberUtils.floatToRawIntBits(this.x);
result = prime * result + NumberUtils.floatToRawIntBits(this.y);
return result;
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./gdx/src/com/badlogic/gdx/utils/compression/lzma/Base.java | // Base.java
package com.badlogic.gdx.utils.compression.lzma;
public class Base {
public static final int kNumRepDistances = 4;
public static final int kNumStates = 12;
public static final int StateInit () {
return 0;
}
public static final int StateUpdateChar (int index) {
if (index < 4) return 0;
if (index < 10) return index - 3;
return index - 6;
}
public static final int StateUpdateMatch (int index) {
return (index < 7 ? 7 : 10);
}
public static final int StateUpdateRep (int index) {
return (index < 7 ? 8 : 11);
}
public static final int StateUpdateShortRep (int index) {
return (index < 7 ? 9 : 11);
}
public static final boolean StateIsCharState (int index) {
return index < 7;
}
public static final int kNumPosSlotBits = 6;
public static final int kDicLogSizeMin = 0;
// public static final int kDicLogSizeMax = 28;
// public static final int kDistTableSizeMax = kDicLogSizeMax * 2;
public static final int kNumLenToPosStatesBits = 2; // it's for speed optimization
public static final int kNumLenToPosStates = 1 << kNumLenToPosStatesBits;
public static final int kMatchMinLen = 2;
public static final int GetLenToPosState (int len) {
len -= kMatchMinLen;
if (len < kNumLenToPosStates) return len;
return (int)(kNumLenToPosStates - 1);
}
public static final int kNumAlignBits = 4;
public static final int kAlignTableSize = 1 << kNumAlignBits;
public static final int kAlignMask = (kAlignTableSize - 1);
public static final int kStartPosModelIndex = 4;
public static final int kEndPosModelIndex = 14;
public static final int kNumPosModels = kEndPosModelIndex - kStartPosModelIndex;
public static final int kNumFullDistances = 1 << (kEndPosModelIndex / 2);
public static final int kNumLitPosStatesBitsEncodingMax = 4;
public static final int kNumLitContextBitsMax = 8;
public static final int kNumPosStatesBitsMax = 4;
public static final int kNumPosStatesMax = (1 << kNumPosStatesBitsMax);
public static final int kNumPosStatesBitsEncodingMax = 4;
public static final int kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax);
public static final int kNumLowLenBits = 3;
public static final int kNumMidLenBits = 3;
public static final int kNumHighLenBits = 8;
public static final int kNumLowLenSymbols = 1 << kNumLowLenBits;
public static final int kNumMidLenSymbols = 1 << kNumMidLenBits;
public static final int kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + (1 << kNumHighLenBits);
public static final int kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1;
}
| // Base.java
package com.badlogic.gdx.utils.compression.lzma;
public class Base {
public static final int kNumRepDistances = 4;
public static final int kNumStates = 12;
public static final int StateInit () {
return 0;
}
public static final int StateUpdateChar (int index) {
if (index < 4) return 0;
if (index < 10) return index - 3;
return index - 6;
}
public static final int StateUpdateMatch (int index) {
return (index < 7 ? 7 : 10);
}
public static final int StateUpdateRep (int index) {
return (index < 7 ? 8 : 11);
}
public static final int StateUpdateShortRep (int index) {
return (index < 7 ? 9 : 11);
}
public static final boolean StateIsCharState (int index) {
return index < 7;
}
public static final int kNumPosSlotBits = 6;
public static final int kDicLogSizeMin = 0;
// public static final int kDicLogSizeMax = 28;
// public static final int kDistTableSizeMax = kDicLogSizeMax * 2;
public static final int kNumLenToPosStatesBits = 2; // it's for speed optimization
public static final int kNumLenToPosStates = 1 << kNumLenToPosStatesBits;
public static final int kMatchMinLen = 2;
public static final int GetLenToPosState (int len) {
len -= kMatchMinLen;
if (len < kNumLenToPosStates) return len;
return (int)(kNumLenToPosStates - 1);
}
public static final int kNumAlignBits = 4;
public static final int kAlignTableSize = 1 << kNumAlignBits;
public static final int kAlignMask = (kAlignTableSize - 1);
public static final int kStartPosModelIndex = 4;
public static final int kEndPosModelIndex = 14;
public static final int kNumPosModels = kEndPosModelIndex - kStartPosModelIndex;
public static final int kNumFullDistances = 1 << (kEndPosModelIndex / 2);
public static final int kNumLitPosStatesBitsEncodingMax = 4;
public static final int kNumLitContextBitsMax = 8;
public static final int kNumPosStatesBitsMax = 4;
public static final int kNumPosStatesMax = (1 << kNumPosStatesBitsMax);
public static final int kNumPosStatesBitsEncodingMax = 4;
public static final int kNumPosStatesEncodingMax = (1 << kNumPosStatesBitsEncodingMax);
public static final int kNumLowLenBits = 3;
public static final int kNumMidLenBits = 3;
public static final int kNumHighLenBits = 8;
public static final int kNumLowLenSymbols = 1 << kNumLowLenBits;
public static final int kNumMidLenSymbols = 1 << kNumMidLenBits;
public static final int kNumLenSymbols = kNumLowLenSymbols + kNumMidLenSymbols + (1 << kNumHighLenBits);
public static final int kMatchMaxLen = kMatchMinLen + kNumLenSymbols - 1;
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btCompoundShapeData.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btCompoundShapeData extends BulletBase {
private long swigCPtr;
protected btCompoundShapeData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btCompoundShapeData, normally you should not need this constructor it's intended for low-level usage. */
public btCompoundShapeData (long cPtr, boolean cMemoryOwn) {
this("btCompoundShapeData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btCompoundShapeData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btCompoundShapeData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setCollisionShapeData (btCollisionShapeData value) {
CollisionJNI.btCompoundShapeData_collisionShapeData_set(swigCPtr, this, btCollisionShapeData.getCPtr(value), value);
}
public btCollisionShapeData getCollisionShapeData () {
long cPtr = CollisionJNI.btCompoundShapeData_collisionShapeData_get(swigCPtr, this);
return (cPtr == 0) ? null : new btCollisionShapeData(cPtr, false);
}
public void setChildShapePtr (btCompoundShapeChildData value) {
CollisionJNI.btCompoundShapeData_childShapePtr_set(swigCPtr, this, btCompoundShapeChildData.getCPtr(value), value);
}
public btCompoundShapeChildData getChildShapePtr () {
long cPtr = CollisionJNI.btCompoundShapeData_childShapePtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btCompoundShapeChildData(cPtr, false);
}
public void setNumChildShapes (int value) {
CollisionJNI.btCompoundShapeData_numChildShapes_set(swigCPtr, this, value);
}
public int getNumChildShapes () {
return CollisionJNI.btCompoundShapeData_numChildShapes_get(swigCPtr, this);
}
public void setCollisionMargin (float value) {
CollisionJNI.btCompoundShapeData_collisionMargin_set(swigCPtr, this, value);
}
public float getCollisionMargin () {
return CollisionJNI.btCompoundShapeData_collisionMargin_get(swigCPtr, this);
}
public btCompoundShapeData () {
this(CollisionJNI.new_btCompoundShapeData(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btCompoundShapeData extends BulletBase {
private long swigCPtr;
protected btCompoundShapeData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btCompoundShapeData, normally you should not need this constructor it's intended for low-level usage. */
public btCompoundShapeData (long cPtr, boolean cMemoryOwn) {
this("btCompoundShapeData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btCompoundShapeData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btCompoundShapeData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setCollisionShapeData (btCollisionShapeData value) {
CollisionJNI.btCompoundShapeData_collisionShapeData_set(swigCPtr, this, btCollisionShapeData.getCPtr(value), value);
}
public btCollisionShapeData getCollisionShapeData () {
long cPtr = CollisionJNI.btCompoundShapeData_collisionShapeData_get(swigCPtr, this);
return (cPtr == 0) ? null : new btCollisionShapeData(cPtr, false);
}
public void setChildShapePtr (btCompoundShapeChildData value) {
CollisionJNI.btCompoundShapeData_childShapePtr_set(swigCPtr, this, btCompoundShapeChildData.getCPtr(value), value);
}
public btCompoundShapeChildData getChildShapePtr () {
long cPtr = CollisionJNI.btCompoundShapeData_childShapePtr_get(swigCPtr, this);
return (cPtr == 0) ? null : new btCompoundShapeChildData(cPtr, false);
}
public void setNumChildShapes (int value) {
CollisionJNI.btCompoundShapeData_numChildShapes_set(swigCPtr, this, value);
}
public int getNumChildShapes () {
return CollisionJNI.btCompoundShapeData_numChildShapes_get(swigCPtr, this);
}
public void setCollisionMargin (float value) {
CollisionJNI.btCompoundShapeData_collisionMargin_set(swigCPtr, this, value);
}
public float getCollisionMargin () {
return CollisionJNI.btCompoundShapeData_collisionMargin_get(swigCPtr, this);
}
public btCompoundShapeData () {
this(CollisionJNI.new_btCompoundShapeData(), true);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btQuantizedBvh.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btQuantizedBvh extends BulletBase {
private long swigCPtr;
protected btQuantizedBvh (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btQuantizedBvh, normally you should not need this constructor it's intended for low-level usage. */
public btQuantizedBvh (long cPtr, boolean cMemoryOwn) {
this("btQuantizedBvh", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btQuantizedBvh obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btQuantizedBvh(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btQuantizedBvh_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btQuantizedBvh_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btQuantizedBvh_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btQuantizedBvh_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btQuantizedBvh_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btQuantizedBvh_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btQuantizedBvh_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btQuantizedBvh_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btQuantizedBvh () {
this(CollisionJNI.new_btQuantizedBvh(), true);
}
public void setQuantizationValues (Vector3 bvhAabbMin, Vector3 bvhAabbMax, float quantizationMargin) {
CollisionJNI.btQuantizedBvh_setQuantizationValues__SWIG_0(swigCPtr, this, bvhAabbMin, bvhAabbMax, quantizationMargin);
}
public void setQuantizationValues (Vector3 bvhAabbMin, Vector3 bvhAabbMax) {
CollisionJNI.btQuantizedBvh_setQuantizationValues__SWIG_1(swigCPtr, this, bvhAabbMin, bvhAabbMax);
}
public SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t getLeafNodeArray () {
return new SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t(
CollisionJNI.btQuantizedBvh_getLeafNodeArray(swigCPtr, this), false);
}
public void buildInternal () {
CollisionJNI.btQuantizedBvh_buildInternal(swigCPtr, this);
}
public void reportAabbOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btQuantizedBvh_reportAabbOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback),
nodeCallback, aabbMin, aabbMax);
}
public void reportRayOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 raySource, Vector3 rayTarget) {
CollisionJNI.btQuantizedBvh_reportRayOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback),
nodeCallback, raySource, rayTarget);
}
public void reportBoxCastOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 raySource, Vector3 rayTarget,
Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btQuantizedBvh_reportBoxCastOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback),
nodeCallback, raySource, rayTarget, aabbMin, aabbMax);
}
public void quantize (java.nio.IntBuffer out, Vector3 point, int isMax) {
assert out.isDirect() : "Buffer must be allocated direct.";
{
CollisionJNI.btQuantizedBvh_quantize(swigCPtr, this, out, point, isMax);
}
}
public void quantizeWithClamp (java.nio.IntBuffer out, Vector3 point2, int isMax) {
assert out.isDirect() : "Buffer must be allocated direct.";
{
CollisionJNI.btQuantizedBvh_quantizeWithClamp(swigCPtr, this, out, point2, isMax);
}
}
public Vector3 unQuantize (java.nio.IntBuffer vecIn) {
assert vecIn.isDirect() : "Buffer must be allocated direct.";
{
return CollisionJNI.btQuantizedBvh_unQuantize(swigCPtr, this, vecIn);
}
}
public void setTraversalMode (int traversalMode) {
CollisionJNI.btQuantizedBvh_setTraversalMode(swigCPtr, this, traversalMode);
}
public SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t getQuantizedNodeArray () {
return new SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t(
CollisionJNI.btQuantizedBvh_getQuantizedNodeArray(swigCPtr, this), false);
}
public SWIGTYPE_p_btAlignedObjectArrayT_btBvhSubtreeInfo_t getSubtreeInfoArray () {
return new SWIGTYPE_p_btAlignedObjectArrayT_btBvhSubtreeInfo_t(
CollisionJNI.btQuantizedBvh_getSubtreeInfoArray(swigCPtr, this), false);
}
public long calculateSerializeBufferSize () {
return CollisionJNI.btQuantizedBvh_calculateSerializeBufferSize(swigCPtr, this);
}
public boolean serialize (long o_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) {
return CollisionJNI.btQuantizedBvh_serialize__SWIG_0(swigCPtr, this, o_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
}
public static btQuantizedBvh deSerializeInPlace (long i_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) {
long cPtr = CollisionJNI.btQuantizedBvh_deSerializeInPlace(i_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
return (cPtr == 0) ? null : new btQuantizedBvh(cPtr, false);
}
public static long getAlignmentSerializationPadding () {
return CollisionJNI.btQuantizedBvh_getAlignmentSerializationPadding();
}
public int calculateSerializeBufferSizeNew () {
return CollisionJNI.btQuantizedBvh_calculateSerializeBufferSizeNew(swigCPtr, this);
}
public String serialize (long dataBuffer, btSerializer serializer) {
return CollisionJNI.btQuantizedBvh_serialize__SWIG_1(swigCPtr, this, dataBuffer, btSerializer.getCPtr(serializer),
serializer);
}
public void deSerializeFloat (btQuantizedBvhFloatData quantizedBvhFloatData) {
CollisionJNI.btQuantizedBvh_deSerializeFloat(swigCPtr, this, btQuantizedBvhFloatData.getCPtr(quantizedBvhFloatData),
quantizedBvhFloatData);
}
public void deSerializeDouble (btQuantizedBvhDoubleData quantizedBvhDoubleData) {
CollisionJNI.btQuantizedBvh_deSerializeDouble(swigCPtr, this, btQuantizedBvhDoubleData.getCPtr(quantizedBvhDoubleData),
quantizedBvhDoubleData);
}
public boolean isQuantized () {
return CollisionJNI.btQuantizedBvh_isQuantized(swigCPtr, this);
}
public final static class btTraversalMode {
public final static int TRAVERSAL_STACKLESS = 0;
public final static int TRAVERSAL_STACKLESS_CACHE_FRIENDLY = TRAVERSAL_STACKLESS + 1;
public final static int TRAVERSAL_RECURSIVE = TRAVERSAL_STACKLESS_CACHE_FRIENDLY + 1;
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btQuantizedBvh extends BulletBase {
private long swigCPtr;
protected btQuantizedBvh (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btQuantizedBvh, normally you should not need this constructor it's intended for low-level usage. */
public btQuantizedBvh (long cPtr, boolean cMemoryOwn) {
this("btQuantizedBvh", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btQuantizedBvh obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btQuantizedBvh(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public long operatorNew (long sizeInBytes) {
return CollisionJNI.btQuantizedBvh_operatorNew__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDelete (long ptr) {
CollisionJNI.btQuantizedBvh_operatorDelete__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNew (long arg0, long ptr) {
return CollisionJNI.btQuantizedBvh_operatorNew__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDelete (long arg0, long arg1) {
CollisionJNI.btQuantizedBvh_operatorDelete__SWIG_1(swigCPtr, this, arg0, arg1);
}
public long operatorNewArray (long sizeInBytes) {
return CollisionJNI.btQuantizedBvh_operatorNewArray__SWIG_0(swigCPtr, this, sizeInBytes);
}
public void operatorDeleteArray (long ptr) {
CollisionJNI.btQuantizedBvh_operatorDeleteArray__SWIG_0(swigCPtr, this, ptr);
}
public long operatorNewArray (long arg0, long ptr) {
return CollisionJNI.btQuantizedBvh_operatorNewArray__SWIG_1(swigCPtr, this, arg0, ptr);
}
public void operatorDeleteArray (long arg0, long arg1) {
CollisionJNI.btQuantizedBvh_operatorDeleteArray__SWIG_1(swigCPtr, this, arg0, arg1);
}
public btQuantizedBvh () {
this(CollisionJNI.new_btQuantizedBvh(), true);
}
public void setQuantizationValues (Vector3 bvhAabbMin, Vector3 bvhAabbMax, float quantizationMargin) {
CollisionJNI.btQuantizedBvh_setQuantizationValues__SWIG_0(swigCPtr, this, bvhAabbMin, bvhAabbMax, quantizationMargin);
}
public void setQuantizationValues (Vector3 bvhAabbMin, Vector3 bvhAabbMax) {
CollisionJNI.btQuantizedBvh_setQuantizationValues__SWIG_1(swigCPtr, this, bvhAabbMin, bvhAabbMax);
}
public SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t getLeafNodeArray () {
return new SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t(
CollisionJNI.btQuantizedBvh_getLeafNodeArray(swigCPtr, this), false);
}
public void buildInternal () {
CollisionJNI.btQuantizedBvh_buildInternal(swigCPtr, this);
}
public void reportAabbOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btQuantizedBvh_reportAabbOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback),
nodeCallback, aabbMin, aabbMax);
}
public void reportRayOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 raySource, Vector3 rayTarget) {
CollisionJNI.btQuantizedBvh_reportRayOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback),
nodeCallback, raySource, rayTarget);
}
public void reportBoxCastOverlappingNodex (btNodeOverlapCallback nodeCallback, Vector3 raySource, Vector3 rayTarget,
Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btQuantizedBvh_reportBoxCastOverlappingNodex(swigCPtr, this, btNodeOverlapCallback.getCPtr(nodeCallback),
nodeCallback, raySource, rayTarget, aabbMin, aabbMax);
}
public void quantize (java.nio.IntBuffer out, Vector3 point, int isMax) {
assert out.isDirect() : "Buffer must be allocated direct.";
{
CollisionJNI.btQuantizedBvh_quantize(swigCPtr, this, out, point, isMax);
}
}
public void quantizeWithClamp (java.nio.IntBuffer out, Vector3 point2, int isMax) {
assert out.isDirect() : "Buffer must be allocated direct.";
{
CollisionJNI.btQuantizedBvh_quantizeWithClamp(swigCPtr, this, out, point2, isMax);
}
}
public Vector3 unQuantize (java.nio.IntBuffer vecIn) {
assert vecIn.isDirect() : "Buffer must be allocated direct.";
{
return CollisionJNI.btQuantizedBvh_unQuantize(swigCPtr, this, vecIn);
}
}
public void setTraversalMode (int traversalMode) {
CollisionJNI.btQuantizedBvh_setTraversalMode(swigCPtr, this, traversalMode);
}
public SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t getQuantizedNodeArray () {
return new SWIGTYPE_p_btAlignedObjectArrayT_btQuantizedBvhNode_t(
CollisionJNI.btQuantizedBvh_getQuantizedNodeArray(swigCPtr, this), false);
}
public SWIGTYPE_p_btAlignedObjectArrayT_btBvhSubtreeInfo_t getSubtreeInfoArray () {
return new SWIGTYPE_p_btAlignedObjectArrayT_btBvhSubtreeInfo_t(
CollisionJNI.btQuantizedBvh_getSubtreeInfoArray(swigCPtr, this), false);
}
public long calculateSerializeBufferSize () {
return CollisionJNI.btQuantizedBvh_calculateSerializeBufferSize(swigCPtr, this);
}
public boolean serialize (long o_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) {
return CollisionJNI.btQuantizedBvh_serialize__SWIG_0(swigCPtr, this, o_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
}
public static btQuantizedBvh deSerializeInPlace (long i_alignedDataBuffer, long i_dataBufferSize, boolean i_swapEndian) {
long cPtr = CollisionJNI.btQuantizedBvh_deSerializeInPlace(i_alignedDataBuffer, i_dataBufferSize, i_swapEndian);
return (cPtr == 0) ? null : new btQuantizedBvh(cPtr, false);
}
public static long getAlignmentSerializationPadding () {
return CollisionJNI.btQuantizedBvh_getAlignmentSerializationPadding();
}
public int calculateSerializeBufferSizeNew () {
return CollisionJNI.btQuantizedBvh_calculateSerializeBufferSizeNew(swigCPtr, this);
}
public String serialize (long dataBuffer, btSerializer serializer) {
return CollisionJNI.btQuantizedBvh_serialize__SWIG_1(swigCPtr, this, dataBuffer, btSerializer.getCPtr(serializer),
serializer);
}
public void deSerializeFloat (btQuantizedBvhFloatData quantizedBvhFloatData) {
CollisionJNI.btQuantizedBvh_deSerializeFloat(swigCPtr, this, btQuantizedBvhFloatData.getCPtr(quantizedBvhFloatData),
quantizedBvhFloatData);
}
public void deSerializeDouble (btQuantizedBvhDoubleData quantizedBvhDoubleData) {
CollisionJNI.btQuantizedBvh_deSerializeDouble(swigCPtr, this, btQuantizedBvhDoubleData.getCPtr(quantizedBvhDoubleData),
quantizedBvhDoubleData);
}
public boolean isQuantized () {
return CollisionJNI.btQuantizedBvh_isQuantized(swigCPtr, this);
}
public final static class btTraversalMode {
public final static int TRAVERSAL_STACKLESS = 0;
public final static int TRAVERSAL_STACKLESS_CACHE_FRIENDLY = TRAVERSAL_STACKLESS + 1;
public final static int TRAVERSAL_RECURSIVE = TRAVERSAL_STACKLESS_CACHE_FRIENDLY + 1;
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./gdx/src/com/badlogic/gdx/math/Vector3.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.math;
import java.io.Serializable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.NumberUtils;
/** Encapsulates a 3D vector. Allows chaining operations by returning a reference to itself in all modification methods.
* @author [email protected] */
public class Vector3 implements Serializable, Vector<Vector3> {
private static final long serialVersionUID = 3840054589595372522L;
/** the x-component of this vector **/
public float x;
/** the y-component of this vector **/
public float y;
/** the z-component of this vector **/
public float z;
public final static Vector3 X = new Vector3(1, 0, 0);
public final static Vector3 Y = new Vector3(0, 1, 0);
public final static Vector3 Z = new Vector3(0, 0, 1);
public final static Vector3 Zero = new Vector3(0, 0, 0);
private final static Matrix4 tmpMat = new Matrix4();
/** Constructs a vector at (0,0,0) */
public Vector3 () {
}
/** Creates a vector with the given components
* @param x The x-component
* @param y The y-component
* @param z The z-component */
public Vector3 (float x, float y, float z) {
this.set(x, y, z);
}
/** Creates a vector from the given vector
* @param vector The vector */
public Vector3 (final Vector3 vector) {
this.set(vector);
}
/** Creates a vector from the given array. The array must have at least 3 elements.
*
* @param values The array */
public Vector3 (final float[] values) {
this.set(values[0], values[1], values[2]);
}
/** Creates a vector from the given vector and z-component
*
* @param vector The vector
* @param z The z-component */
public Vector3 (final Vector2 vector, float z) {
this.set(vector.x, vector.y, z);
}
/** Sets the vector to the given components
*
* @param x The x-component
* @param y The y-component
* @param z The z-component
* @return this vector for chaining */
public Vector3 set (float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
@Override
public Vector3 set (final Vector3 vector) {
return this.set(vector.x, vector.y, vector.z);
}
/** Sets the components from the array. The array must have at least 3 elements
*
* @param values The array
* @return this vector for chaining */
public Vector3 set (final float[] values) {
return this.set(values[0], values[1], values[2]);
}
/** Sets the components of the given vector and z-component
*
* @param vector The vector
* @param z The z-component
* @return This vector for chaining */
public Vector3 set (final Vector2 vector, float z) {
return this.set(vector.x, vector.y, z);
}
/** Sets the components from the given spherical coordinate
* @param azimuthalAngle The angle between x-axis in radians [0, 2pi]
* @param polarAngle The angle between z-axis in radians [0, pi]
* @return This vector for chaining */
public Vector3 setFromSpherical (float azimuthalAngle, float polarAngle) {
float cosPolar = MathUtils.cos(polarAngle);
float sinPolar = MathUtils.sin(polarAngle);
float cosAzim = MathUtils.cos(azimuthalAngle);
float sinAzim = MathUtils.sin(azimuthalAngle);
return this.set(cosAzim * sinPolar, sinAzim * sinPolar, cosPolar);
}
@Override
public Vector3 setToRandomDirection () {
float u = MathUtils.random();
float v = MathUtils.random();
float theta = MathUtils.PI2 * u; // azimuthal angle
float phi = (float)Math.acos(2f * v - 1f); // polar angle
return this.setFromSpherical(theta, phi);
}
@Override
public Vector3 cpy () {
return new Vector3(this);
}
@Override
public Vector3 add (final Vector3 vector) {
return this.add(vector.x, vector.y, vector.z);
}
/** Adds the given vector to this component
* @param x The x-component of the other vector
* @param y The y-component of the other vector
* @param z The z-component of the other vector
* @return This vector for chaining. */
public Vector3 add (float x, float y, float z) {
return this.set(this.x + x, this.y + y, this.z + z);
}
/** Adds the given value to all three components of the vector.
*
* @param values The value
* @return This vector for chaining */
public Vector3 add (float values) {
return this.set(this.x + values, this.y + values, this.z + values);
}
@Override
public Vector3 sub (final Vector3 a_vec) {
return this.sub(a_vec.x, a_vec.y, a_vec.z);
}
/** Subtracts the other vector from this vector.
*
* @param x The x-component of the other vector
* @param y The y-component of the other vector
* @param z The z-component of the other vector
* @return This vector for chaining */
public Vector3 sub (float x, float y, float z) {
return this.set(this.x - x, this.y - y, this.z - z);
}
/** Subtracts the given value from all components of this vector
*
* @param value The value
* @return This vector for chaining */
public Vector3 sub (float value) {
return this.set(this.x - value, this.y - value, this.z - value);
}
@Override
public Vector3 scl (float scalar) {
return this.set(this.x * scalar, this.y * scalar, this.z * scalar);
}
@Override
public Vector3 scl (final Vector3 other) {
return this.set(x * other.x, y * other.y, z * other.z);
}
/** Scales this vector by the given values
* @param vx X value
* @param vy Y value
* @param vz Z value
* @return This vector for chaining */
public Vector3 scl (float vx, float vy, float vz) {
return this.set(this.x * vx, this.y * vy, this.z * vz);
}
@Override
public Vector3 mulAdd (Vector3 vec, float scalar) {
this.x += vec.x * scalar;
this.y += vec.y * scalar;
this.z += vec.z * scalar;
return this;
}
@Override
public Vector3 mulAdd (Vector3 vec, Vector3 mulVec) {
this.x += vec.x * mulVec.x;
this.y += vec.y * mulVec.y;
this.z += vec.z * mulVec.z;
return this;
}
/** @return The Euclidean length */
public static float len (final float x, final float y, final float z) {
return (float)Math.sqrt(x * x + y * y + z * z);
}
@Override
public float len () {
return (float)Math.sqrt(x * x + y * y + z * z);
}
/** @return The squared Euclidean length */
public static float len2 (final float x, final float y, final float z) {
return x * x + y * y + z * z;
}
@Override
public float len2 () {
return x * x + y * y + z * z;
}
/** Returns true if this vector and the vector parameter have identical components.
* @param vector The other vector
* @return Whether this and the other vector are equal with exact precision */
public boolean idt (final Vector3 vector) {
return x == vector.x && y == vector.y && z == vector.z;
}
/** @return The Euclidean distance between the two specified vectors */
public static float dst (final float x1, final float y1, final float z1, final float x2, final float y2, final float z2) {
final float a = x2 - x1;
final float b = y2 - y1;
final float c = z2 - z1;
return (float)Math.sqrt(a * a + b * b + c * c);
}
@Override
public float dst (final Vector3 vector) {
final float a = vector.x - x;
final float b = vector.y - y;
final float c = vector.z - z;
return (float)Math.sqrt(a * a + b * b + c * c);
}
/** @return the distance between this point and the given point */
public float dst (float x, float y, float z) {
final float a = x - this.x;
final float b = y - this.y;
final float c = z - this.z;
return (float)Math.sqrt(a * a + b * b + c * c);
}
/** @return the squared distance between the given points */
public static float dst2 (final float x1, final float y1, final float z1, final float x2, final float y2, final float z2) {
final float a = x2 - x1;
final float b = y2 - y1;
final float c = z2 - z1;
return a * a + b * b + c * c;
}
@Override
public float dst2 (Vector3 point) {
final float a = point.x - x;
final float b = point.y - y;
final float c = point.z - z;
return a * a + b * b + c * c;
}
/** Returns the squared distance between this point and the given point
* @param x The x-component of the other point
* @param y The y-component of the other point
* @param z The z-component of the other point
* @return The squared distance */
public float dst2 (float x, float y, float z) {
final float a = x - this.x;
final float b = y - this.y;
final float c = z - this.z;
return a * a + b * b + c * c;
}
@Override
public Vector3 nor () {
final float len2 = this.len2();
if (len2 == 0f || len2 == 1f) return this;
return this.scl(1f / (float)Math.sqrt(len2));
}
/** @return The dot product between the two vectors */
public static float dot (float x1, float y1, float z1, float x2, float y2, float z2) {
return x1 * x2 + y1 * y2 + z1 * z2;
}
@Override
public float dot (final Vector3 vector) {
return x * vector.x + y * vector.y + z * vector.z;
}
/** Returns the dot product between this and the given vector.
* @param x The x-component of the other vector
* @param y The y-component of the other vector
* @param z The z-component of the other vector
* @return The dot product */
public float dot (float x, float y, float z) {
return this.x * x + this.y * y + this.z * z;
}
/** Sets this vector to the cross product between it and the other vector.
* @param vector The other vector
* @return This vector for chaining */
public Vector3 crs (final Vector3 vector) {
return this.set(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x);
}
/** Sets this vector to the cross product between it and the other vector.
* @param x The x-component of the other vector
* @param y The y-component of the other vector
* @param z The z-component of the other vector
* @return This vector for chaining */
public Vector3 crs (float x, float y, float z) {
return this.set(this.y * z - this.z * y, this.z * x - this.x * z, this.x * y - this.y * x);
}
/** Left-multiplies the vector by the given 4x3 column major matrix. The matrix should be composed by a 3x3 matrix representing
* rotation and scale plus a 1x3 matrix representing the translation.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 mul4x3 (float[] matrix) {
return set(x * matrix[0] + y * matrix[3] + z * matrix[6] + matrix[9],
x * matrix[1] + y * matrix[4] + z * matrix[7] + matrix[10], x * matrix[2] + y * matrix[5] + z * matrix[8] + matrix[11]);
}
/** Left-multiplies the vector by the given matrix, assuming the fourth (w) component of the vector is 1.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 mul (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02] + l_mat[Matrix4.M03],
x * l_mat[Matrix4.M10] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12] + l_mat[Matrix4.M13],
x * l_mat[Matrix4.M20] + y * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22] + l_mat[Matrix4.M23]);
}
/** Multiplies the vector by the transpose of the given matrix, assuming the fourth (w) component of the vector is 1.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 traMul (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M10] + z * l_mat[Matrix4.M20] + l_mat[Matrix4.M30],
x * l_mat[Matrix4.M01] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M21] + l_mat[Matrix4.M31],
x * l_mat[Matrix4.M02] + y * l_mat[Matrix4.M12] + z * l_mat[Matrix4.M22] + l_mat[Matrix4.M32]);
}
/** Left-multiplies the vector by the given matrix.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 mul (Matrix3 matrix) {
final float[] l_mat = matrix.val;
return set(x * l_mat[Matrix3.M00] + y * l_mat[Matrix3.M01] + z * l_mat[Matrix3.M02],
x * l_mat[Matrix3.M10] + y * l_mat[Matrix3.M11] + z * l_mat[Matrix3.M12],
x * l_mat[Matrix3.M20] + y * l_mat[Matrix3.M21] + z * l_mat[Matrix3.M22]);
}
/** Multiplies the vector by the transpose of the given matrix.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 traMul (Matrix3 matrix) {
final float[] l_mat = matrix.val;
return set(x * l_mat[Matrix3.M00] + y * l_mat[Matrix3.M10] + z * l_mat[Matrix3.M20],
x * l_mat[Matrix3.M01] + y * l_mat[Matrix3.M11] + z * l_mat[Matrix3.M21],
x * l_mat[Matrix3.M02] + y * l_mat[Matrix3.M12] + z * l_mat[Matrix3.M22]);
}
/** Multiplies the vector by the given {@link Quaternion}.
* @return This vector for chaining */
public Vector3 mul (final Quaternion quat) {
return quat.transform(this);
}
/** Multiplies this vector by the given matrix dividing by w, assuming the fourth (w) component of the vector is 1. This is
* mostly used to project/unproject vectors via a perspective projection matrix.
*
* @param matrix The matrix.
* @return This vector for chaining */
public Vector3 prj (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
final float l_w = 1f / (x * l_mat[Matrix4.M30] + y * l_mat[Matrix4.M31] + z * l_mat[Matrix4.M32] + l_mat[Matrix4.M33]);
return this.set((x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02] + l_mat[Matrix4.M03]) * l_w,
(x * l_mat[Matrix4.M10] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12] + l_mat[Matrix4.M13]) * l_w,
(x * l_mat[Matrix4.M20] + y * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22] + l_mat[Matrix4.M23]) * l_w);
}
/** Multiplies this vector by the first three columns of the matrix, essentially only applying rotation and scaling.
*
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 rot (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02],
x * l_mat[Matrix4.M10] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12],
x * l_mat[Matrix4.M20] + y * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22]);
}
/** Multiplies this vector by the transpose of the first three columns of the matrix. Note: only works for translation and
* rotation, does not work for scaling. For those, use {@link #rot(Matrix4)} with {@link Matrix4#inv()}.
* @param matrix The transformation matrix
* @return The vector for chaining */
public Vector3 unrotate (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M10] + z * l_mat[Matrix4.M20],
x * l_mat[Matrix4.M01] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M21],
x * l_mat[Matrix4.M02] + y * l_mat[Matrix4.M12] + z * l_mat[Matrix4.M22]);
}
/** Translates this vector in the direction opposite to the translation of the matrix and the multiplies this vector by the
* transpose of the first three columns of the matrix. Note: only works for translation and rotation, does not work for
* scaling. For those, use {@link #mul(Matrix4)} with {@link Matrix4#inv()}.
* @param matrix The transformation matrix
* @return The vector for chaining */
public Vector3 untransform (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
x -= l_mat[Matrix4.M03];
y -= l_mat[Matrix4.M03];
z -= l_mat[Matrix4.M03];
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M10] + z * l_mat[Matrix4.M20],
x * l_mat[Matrix4.M01] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M21],
x * l_mat[Matrix4.M02] + y * l_mat[Matrix4.M12] + z * l_mat[Matrix4.M22]);
}
/** Rotates this vector by the given angle in degrees around the given axis.
*
* @param degrees the angle in degrees
* @param axisX the x-component of the axis
* @param axisY the y-component of the axis
* @param axisZ the z-component of the axis
* @return This vector for chaining */
public Vector3 rotate (float degrees, float axisX, float axisY, float axisZ) {
return this.mul(tmpMat.setToRotation(axisX, axisY, axisZ, degrees));
}
/** Rotates this vector by the given angle in radians around the given axis.
*
* @param radians the angle in radians
* @param axisX the x-component of the axis
* @param axisY the y-component of the axis
* @param axisZ the z-component of the axis
* @return This vector for chaining */
public Vector3 rotateRad (float radians, float axisX, float axisY, float axisZ) {
return this.mul(tmpMat.setToRotationRad(axisX, axisY, axisZ, radians));
}
/** Rotates this vector by the given angle in degrees around the given axis.
*
* @param axis the axis
* @param degrees the angle in degrees
* @return This vector for chaining */
public Vector3 rotate (final Vector3 axis, float degrees) {
tmpMat.setToRotation(axis, degrees);
return this.mul(tmpMat);
}
/** Rotates this vector by the given angle in radians around the given axis.
*
* @param axis the axis
* @param radians the angle in radians
* @return This vector for chaining */
public Vector3 rotateRad (final Vector3 axis, float radians) {
tmpMat.setToRotationRad(axis, radians);
return this.mul(tmpMat);
}
@Override
public boolean isUnit () {
return isUnit(0.000000001f);
}
@Override
public boolean isUnit (final float margin) {
return Math.abs(len2() - 1f) < margin;
}
@Override
public boolean isZero () {
return x == 0 && y == 0 && z == 0;
}
@Override
public boolean isZero (final float margin) {
return len2() < margin;
}
@Override
public boolean isOnLine (Vector3 other, float epsilon) {
return len2(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x) <= epsilon;
}
@Override
public boolean isOnLine (Vector3 other) {
return len2(y * other.z - z * other.y, z * other.x - x * other.z,
x * other.y - y * other.x) <= MathUtils.FLOAT_ROUNDING_ERROR;
}
@Override
public boolean isCollinear (Vector3 other, float epsilon) {
return isOnLine(other, epsilon) && hasSameDirection(other);
}
@Override
public boolean isCollinear (Vector3 other) {
return isOnLine(other) && hasSameDirection(other);
}
@Override
public boolean isCollinearOpposite (Vector3 other, float epsilon) {
return isOnLine(other, epsilon) && hasOppositeDirection(other);
}
@Override
public boolean isCollinearOpposite (Vector3 other) {
return isOnLine(other) && hasOppositeDirection(other);
}
@Override
public boolean isPerpendicular (Vector3 vector) {
return MathUtils.isZero(dot(vector));
}
@Override
public boolean isPerpendicular (Vector3 vector, float epsilon) {
return MathUtils.isZero(dot(vector), epsilon);
}
@Override
public boolean hasSameDirection (Vector3 vector) {
return dot(vector) > 0;
}
@Override
public boolean hasOppositeDirection (Vector3 vector) {
return dot(vector) < 0;
}
@Override
public Vector3 lerp (final Vector3 target, float alpha) {
x += alpha * (target.x - x);
y += alpha * (target.y - y);
z += alpha * (target.z - z);
return this;
}
@Override
public Vector3 interpolate (Vector3 target, float alpha, Interpolation interpolator) {
return lerp(target, interpolator.apply(0f, 1f, alpha));
}
/** Spherically interpolates between this vector and the target vector by alpha which is in the range [0,1]. The result is
* stored in this vector.
*
* @param target The target vector
* @param alpha The interpolation coefficient
* @return This vector for chaining. */
public Vector3 slerp (final Vector3 target, float alpha) {
final float dot = dot(target);
// If the inputs are too close for comfort, simply linearly interpolate.
if (dot > 0.9995 || dot < -0.9995) return lerp(target, alpha);
// theta0 = angle between input vectors
final float theta0 = (float)Math.acos(dot);
// theta = angle between this vector and result
final float theta = theta0 * alpha;
final float st = (float)Math.sin(theta);
final float tx = target.x - x * dot;
final float ty = target.y - y * dot;
final float tz = target.z - z * dot;
final float l2 = tx * tx + ty * ty + tz * tz;
final float dl = st * ((l2 < 0.0001f) ? 1f : 1f / (float)Math.sqrt(l2));
return scl((float)Math.cos(theta)).add(tx * dl, ty * dl, tz * dl).nor();
}
/** Converts this {@code Vector3} to a string in the format {@code (x,y,z)}.
* @return a string representation of this object. */
@Override
public String toString () {
return "(" + x + "," + y + "," + z + ")";
}
/** Sets this {@code Vector3} to the value represented by the specified string according to the format of {@link #toString()}.
* @param v the string.
* @return this vector for chaining */
public Vector3 fromString (String v) {
int s0 = v.indexOf(',', 1);
int s1 = v.indexOf(',', s0 + 1);
if (s0 != -1 && s1 != -1 && v.charAt(0) == '(' && v.charAt(v.length() - 1) == ')') {
try {
float x = Float.parseFloat(v.substring(1, s0));
float y = Float.parseFloat(v.substring(s0 + 1, s1));
float z = Float.parseFloat(v.substring(s1 + 1, v.length() - 1));
return this.set(x, y, z);
} catch (NumberFormatException ex) {
// Throw a GdxRuntimeException
}
}
throw new GdxRuntimeException("Malformed Vector3: " + v);
}
@Override
public Vector3 limit (float limit) {
return limit2(limit * limit);
}
@Override
public Vector3 limit2 (float limit2) {
float len2 = len2();
if (len2 > limit2) {
scl((float)Math.sqrt(limit2 / len2));
}
return this;
}
@Override
public Vector3 setLength (float len) {
return setLength2(len * len);
}
@Override
public Vector3 setLength2 (float len2) {
float oldLen2 = len2();
return (oldLen2 == 0 || oldLen2 == len2) ? this : scl((float)Math.sqrt(len2 / oldLen2));
}
@Override
public Vector3 clamp (float min, float max) {
final float len2 = len2();
if (len2 == 0f) return this;
float max2 = max * max;
if (len2 > max2) return scl((float)Math.sqrt(max2 / len2));
float min2 = min * min;
if (len2 < min2) return scl((float)Math.sqrt(min2 / len2));
return this;
}
@Override
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + NumberUtils.floatToIntBits(x);
result = prime * result + NumberUtils.floatToIntBits(y);
result = prime * result + NumberUtils.floatToIntBits(z);
return result;
}
@Override
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector3 other = (Vector3)obj;
if (NumberUtils.floatToIntBits(x) != NumberUtils.floatToIntBits(other.x)) return false;
if (NumberUtils.floatToIntBits(y) != NumberUtils.floatToIntBits(other.y)) return false;
if (NumberUtils.floatToIntBits(z) != NumberUtils.floatToIntBits(other.z)) return false;
return true;
}
@Override
public boolean epsilonEquals (final Vector3 other, float epsilon) {
if (other == null) return false;
if (Math.abs(other.x - x) > epsilon) return false;
if (Math.abs(other.y - y) > epsilon) return false;
if (Math.abs(other.z - z) > epsilon) return false;
return true;
}
/** Compares this vector with the other vector, using the supplied epsilon for fuzzy equality testing.
* @return whether the vectors are the same. */
public boolean epsilonEquals (float x, float y, float z, float epsilon) {
if (Math.abs(x - this.x) > epsilon) return false;
if (Math.abs(y - this.y) > epsilon) return false;
if (Math.abs(z - this.z) > epsilon) return false;
return true;
}
/** Compares this vector with the other vector using MathUtils.FLOAT_ROUNDING_ERROR for fuzzy equality testing
*
* @param other other vector to compare
* @return true if vector are equal, otherwise false */
public boolean epsilonEquals (final Vector3 other) {
return epsilonEquals(other, MathUtils.FLOAT_ROUNDING_ERROR);
}
/** Compares this vector with the other vector using MathUtils.FLOAT_ROUNDING_ERROR for fuzzy equality testing
*
* @param x x component of the other vector to compare
* @param y y component of the other vector to compare
* @param z z component of the other vector to compare
* @return true if vector are equal, otherwise false */
public boolean epsilonEquals (float x, float y, float z) {
return epsilonEquals(x, y, z, MathUtils.FLOAT_ROUNDING_ERROR);
}
@Override
public Vector3 setZero () {
this.x = 0;
this.y = 0;
this.z = 0;
return this;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.math;
import java.io.Serializable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.NumberUtils;
/** Encapsulates a 3D vector. Allows chaining operations by returning a reference to itself in all modification methods.
* @author [email protected] */
public class Vector3 implements Serializable, Vector<Vector3> {
private static final long serialVersionUID = 3840054589595372522L;
/** the x-component of this vector **/
public float x;
/** the y-component of this vector **/
public float y;
/** the z-component of this vector **/
public float z;
public final static Vector3 X = new Vector3(1, 0, 0);
public final static Vector3 Y = new Vector3(0, 1, 0);
public final static Vector3 Z = new Vector3(0, 0, 1);
public final static Vector3 Zero = new Vector3(0, 0, 0);
private final static Matrix4 tmpMat = new Matrix4();
/** Constructs a vector at (0,0,0) */
public Vector3 () {
}
/** Creates a vector with the given components
* @param x The x-component
* @param y The y-component
* @param z The z-component */
public Vector3 (float x, float y, float z) {
this.set(x, y, z);
}
/** Creates a vector from the given vector
* @param vector The vector */
public Vector3 (final Vector3 vector) {
this.set(vector);
}
/** Creates a vector from the given array. The array must have at least 3 elements.
*
* @param values The array */
public Vector3 (final float[] values) {
this.set(values[0], values[1], values[2]);
}
/** Creates a vector from the given vector and z-component
*
* @param vector The vector
* @param z The z-component */
public Vector3 (final Vector2 vector, float z) {
this.set(vector.x, vector.y, z);
}
/** Sets the vector to the given components
*
* @param x The x-component
* @param y The y-component
* @param z The z-component
* @return this vector for chaining */
public Vector3 set (float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
@Override
public Vector3 set (final Vector3 vector) {
return this.set(vector.x, vector.y, vector.z);
}
/** Sets the components from the array. The array must have at least 3 elements
*
* @param values The array
* @return this vector for chaining */
public Vector3 set (final float[] values) {
return this.set(values[0], values[1], values[2]);
}
/** Sets the components of the given vector and z-component
*
* @param vector The vector
* @param z The z-component
* @return This vector for chaining */
public Vector3 set (final Vector2 vector, float z) {
return this.set(vector.x, vector.y, z);
}
/** Sets the components from the given spherical coordinate
* @param azimuthalAngle The angle between x-axis in radians [0, 2pi]
* @param polarAngle The angle between z-axis in radians [0, pi]
* @return This vector for chaining */
public Vector3 setFromSpherical (float azimuthalAngle, float polarAngle) {
float cosPolar = MathUtils.cos(polarAngle);
float sinPolar = MathUtils.sin(polarAngle);
float cosAzim = MathUtils.cos(azimuthalAngle);
float sinAzim = MathUtils.sin(azimuthalAngle);
return this.set(cosAzim * sinPolar, sinAzim * sinPolar, cosPolar);
}
@Override
public Vector3 setToRandomDirection () {
float u = MathUtils.random();
float v = MathUtils.random();
float theta = MathUtils.PI2 * u; // azimuthal angle
float phi = (float)Math.acos(2f * v - 1f); // polar angle
return this.setFromSpherical(theta, phi);
}
@Override
public Vector3 cpy () {
return new Vector3(this);
}
@Override
public Vector3 add (final Vector3 vector) {
return this.add(vector.x, vector.y, vector.z);
}
/** Adds the given vector to this component
* @param x The x-component of the other vector
* @param y The y-component of the other vector
* @param z The z-component of the other vector
* @return This vector for chaining. */
public Vector3 add (float x, float y, float z) {
return this.set(this.x + x, this.y + y, this.z + z);
}
/** Adds the given value to all three components of the vector.
*
* @param values The value
* @return This vector for chaining */
public Vector3 add (float values) {
return this.set(this.x + values, this.y + values, this.z + values);
}
@Override
public Vector3 sub (final Vector3 a_vec) {
return this.sub(a_vec.x, a_vec.y, a_vec.z);
}
/** Subtracts the other vector from this vector.
*
* @param x The x-component of the other vector
* @param y The y-component of the other vector
* @param z The z-component of the other vector
* @return This vector for chaining */
public Vector3 sub (float x, float y, float z) {
return this.set(this.x - x, this.y - y, this.z - z);
}
/** Subtracts the given value from all components of this vector
*
* @param value The value
* @return This vector for chaining */
public Vector3 sub (float value) {
return this.set(this.x - value, this.y - value, this.z - value);
}
@Override
public Vector3 scl (float scalar) {
return this.set(this.x * scalar, this.y * scalar, this.z * scalar);
}
@Override
public Vector3 scl (final Vector3 other) {
return this.set(x * other.x, y * other.y, z * other.z);
}
/** Scales this vector by the given values
* @param vx X value
* @param vy Y value
* @param vz Z value
* @return This vector for chaining */
public Vector3 scl (float vx, float vy, float vz) {
return this.set(this.x * vx, this.y * vy, this.z * vz);
}
@Override
public Vector3 mulAdd (Vector3 vec, float scalar) {
this.x += vec.x * scalar;
this.y += vec.y * scalar;
this.z += vec.z * scalar;
return this;
}
@Override
public Vector3 mulAdd (Vector3 vec, Vector3 mulVec) {
this.x += vec.x * mulVec.x;
this.y += vec.y * mulVec.y;
this.z += vec.z * mulVec.z;
return this;
}
/** @return The Euclidean length */
public static float len (final float x, final float y, final float z) {
return (float)Math.sqrt(x * x + y * y + z * z);
}
@Override
public float len () {
return (float)Math.sqrt(x * x + y * y + z * z);
}
/** @return The squared Euclidean length */
public static float len2 (final float x, final float y, final float z) {
return x * x + y * y + z * z;
}
@Override
public float len2 () {
return x * x + y * y + z * z;
}
/** Returns true if this vector and the vector parameter have identical components.
* @param vector The other vector
* @return Whether this and the other vector are equal with exact precision */
public boolean idt (final Vector3 vector) {
return x == vector.x && y == vector.y && z == vector.z;
}
/** @return The Euclidean distance between the two specified vectors */
public static float dst (final float x1, final float y1, final float z1, final float x2, final float y2, final float z2) {
final float a = x2 - x1;
final float b = y2 - y1;
final float c = z2 - z1;
return (float)Math.sqrt(a * a + b * b + c * c);
}
@Override
public float dst (final Vector3 vector) {
final float a = vector.x - x;
final float b = vector.y - y;
final float c = vector.z - z;
return (float)Math.sqrt(a * a + b * b + c * c);
}
/** @return the distance between this point and the given point */
public float dst (float x, float y, float z) {
final float a = x - this.x;
final float b = y - this.y;
final float c = z - this.z;
return (float)Math.sqrt(a * a + b * b + c * c);
}
/** @return the squared distance between the given points */
public static float dst2 (final float x1, final float y1, final float z1, final float x2, final float y2, final float z2) {
final float a = x2 - x1;
final float b = y2 - y1;
final float c = z2 - z1;
return a * a + b * b + c * c;
}
@Override
public float dst2 (Vector3 point) {
final float a = point.x - x;
final float b = point.y - y;
final float c = point.z - z;
return a * a + b * b + c * c;
}
/** Returns the squared distance between this point and the given point
* @param x The x-component of the other point
* @param y The y-component of the other point
* @param z The z-component of the other point
* @return The squared distance */
public float dst2 (float x, float y, float z) {
final float a = x - this.x;
final float b = y - this.y;
final float c = z - this.z;
return a * a + b * b + c * c;
}
@Override
public Vector3 nor () {
final float len2 = this.len2();
if (len2 == 0f || len2 == 1f) return this;
return this.scl(1f / (float)Math.sqrt(len2));
}
/** @return The dot product between the two vectors */
public static float dot (float x1, float y1, float z1, float x2, float y2, float z2) {
return x1 * x2 + y1 * y2 + z1 * z2;
}
@Override
public float dot (final Vector3 vector) {
return x * vector.x + y * vector.y + z * vector.z;
}
/** Returns the dot product between this and the given vector.
* @param x The x-component of the other vector
* @param y The y-component of the other vector
* @param z The z-component of the other vector
* @return The dot product */
public float dot (float x, float y, float z) {
return this.x * x + this.y * y + this.z * z;
}
/** Sets this vector to the cross product between it and the other vector.
* @param vector The other vector
* @return This vector for chaining */
public Vector3 crs (final Vector3 vector) {
return this.set(y * vector.z - z * vector.y, z * vector.x - x * vector.z, x * vector.y - y * vector.x);
}
/** Sets this vector to the cross product between it and the other vector.
* @param x The x-component of the other vector
* @param y The y-component of the other vector
* @param z The z-component of the other vector
* @return This vector for chaining */
public Vector3 crs (float x, float y, float z) {
return this.set(this.y * z - this.z * y, this.z * x - this.x * z, this.x * y - this.y * x);
}
/** Left-multiplies the vector by the given 4x3 column major matrix. The matrix should be composed by a 3x3 matrix representing
* rotation and scale plus a 1x3 matrix representing the translation.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 mul4x3 (float[] matrix) {
return set(x * matrix[0] + y * matrix[3] + z * matrix[6] + matrix[9],
x * matrix[1] + y * matrix[4] + z * matrix[7] + matrix[10], x * matrix[2] + y * matrix[5] + z * matrix[8] + matrix[11]);
}
/** Left-multiplies the vector by the given matrix, assuming the fourth (w) component of the vector is 1.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 mul (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02] + l_mat[Matrix4.M03],
x * l_mat[Matrix4.M10] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12] + l_mat[Matrix4.M13],
x * l_mat[Matrix4.M20] + y * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22] + l_mat[Matrix4.M23]);
}
/** Multiplies the vector by the transpose of the given matrix, assuming the fourth (w) component of the vector is 1.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 traMul (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M10] + z * l_mat[Matrix4.M20] + l_mat[Matrix4.M30],
x * l_mat[Matrix4.M01] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M21] + l_mat[Matrix4.M31],
x * l_mat[Matrix4.M02] + y * l_mat[Matrix4.M12] + z * l_mat[Matrix4.M22] + l_mat[Matrix4.M32]);
}
/** Left-multiplies the vector by the given matrix.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 mul (Matrix3 matrix) {
final float[] l_mat = matrix.val;
return set(x * l_mat[Matrix3.M00] + y * l_mat[Matrix3.M01] + z * l_mat[Matrix3.M02],
x * l_mat[Matrix3.M10] + y * l_mat[Matrix3.M11] + z * l_mat[Matrix3.M12],
x * l_mat[Matrix3.M20] + y * l_mat[Matrix3.M21] + z * l_mat[Matrix3.M22]);
}
/** Multiplies the vector by the transpose of the given matrix.
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 traMul (Matrix3 matrix) {
final float[] l_mat = matrix.val;
return set(x * l_mat[Matrix3.M00] + y * l_mat[Matrix3.M10] + z * l_mat[Matrix3.M20],
x * l_mat[Matrix3.M01] + y * l_mat[Matrix3.M11] + z * l_mat[Matrix3.M21],
x * l_mat[Matrix3.M02] + y * l_mat[Matrix3.M12] + z * l_mat[Matrix3.M22]);
}
/** Multiplies the vector by the given {@link Quaternion}.
* @return This vector for chaining */
public Vector3 mul (final Quaternion quat) {
return quat.transform(this);
}
/** Multiplies this vector by the given matrix dividing by w, assuming the fourth (w) component of the vector is 1. This is
* mostly used to project/unproject vectors via a perspective projection matrix.
*
* @param matrix The matrix.
* @return This vector for chaining */
public Vector3 prj (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
final float l_w = 1f / (x * l_mat[Matrix4.M30] + y * l_mat[Matrix4.M31] + z * l_mat[Matrix4.M32] + l_mat[Matrix4.M33]);
return this.set((x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02] + l_mat[Matrix4.M03]) * l_w,
(x * l_mat[Matrix4.M10] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12] + l_mat[Matrix4.M13]) * l_w,
(x * l_mat[Matrix4.M20] + y * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22] + l_mat[Matrix4.M23]) * l_w);
}
/** Multiplies this vector by the first three columns of the matrix, essentially only applying rotation and scaling.
*
* @param matrix The matrix
* @return This vector for chaining */
public Vector3 rot (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M01] + z * l_mat[Matrix4.M02],
x * l_mat[Matrix4.M10] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M12],
x * l_mat[Matrix4.M20] + y * l_mat[Matrix4.M21] + z * l_mat[Matrix4.M22]);
}
/** Multiplies this vector by the transpose of the first three columns of the matrix. Note: only works for translation and
* rotation, does not work for scaling. For those, use {@link #rot(Matrix4)} with {@link Matrix4#inv()}.
* @param matrix The transformation matrix
* @return The vector for chaining */
public Vector3 unrotate (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M10] + z * l_mat[Matrix4.M20],
x * l_mat[Matrix4.M01] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M21],
x * l_mat[Matrix4.M02] + y * l_mat[Matrix4.M12] + z * l_mat[Matrix4.M22]);
}
/** Translates this vector in the direction opposite to the translation of the matrix and the multiplies this vector by the
* transpose of the first three columns of the matrix. Note: only works for translation and rotation, does not work for
* scaling. For those, use {@link #mul(Matrix4)} with {@link Matrix4#inv()}.
* @param matrix The transformation matrix
* @return The vector for chaining */
public Vector3 untransform (final Matrix4 matrix) {
final float[] l_mat = matrix.val;
x -= l_mat[Matrix4.M03];
y -= l_mat[Matrix4.M03];
z -= l_mat[Matrix4.M03];
return this.set(x * l_mat[Matrix4.M00] + y * l_mat[Matrix4.M10] + z * l_mat[Matrix4.M20],
x * l_mat[Matrix4.M01] + y * l_mat[Matrix4.M11] + z * l_mat[Matrix4.M21],
x * l_mat[Matrix4.M02] + y * l_mat[Matrix4.M12] + z * l_mat[Matrix4.M22]);
}
/** Rotates this vector by the given angle in degrees around the given axis.
*
* @param degrees the angle in degrees
* @param axisX the x-component of the axis
* @param axisY the y-component of the axis
* @param axisZ the z-component of the axis
* @return This vector for chaining */
public Vector3 rotate (float degrees, float axisX, float axisY, float axisZ) {
return this.mul(tmpMat.setToRotation(axisX, axisY, axisZ, degrees));
}
/** Rotates this vector by the given angle in radians around the given axis.
*
* @param radians the angle in radians
* @param axisX the x-component of the axis
* @param axisY the y-component of the axis
* @param axisZ the z-component of the axis
* @return This vector for chaining */
public Vector3 rotateRad (float radians, float axisX, float axisY, float axisZ) {
return this.mul(tmpMat.setToRotationRad(axisX, axisY, axisZ, radians));
}
/** Rotates this vector by the given angle in degrees around the given axis.
*
* @param axis the axis
* @param degrees the angle in degrees
* @return This vector for chaining */
public Vector3 rotate (final Vector3 axis, float degrees) {
tmpMat.setToRotation(axis, degrees);
return this.mul(tmpMat);
}
/** Rotates this vector by the given angle in radians around the given axis.
*
* @param axis the axis
* @param radians the angle in radians
* @return This vector for chaining */
public Vector3 rotateRad (final Vector3 axis, float radians) {
tmpMat.setToRotationRad(axis, radians);
return this.mul(tmpMat);
}
@Override
public boolean isUnit () {
return isUnit(0.000000001f);
}
@Override
public boolean isUnit (final float margin) {
return Math.abs(len2() - 1f) < margin;
}
@Override
public boolean isZero () {
return x == 0 && y == 0 && z == 0;
}
@Override
public boolean isZero (final float margin) {
return len2() < margin;
}
@Override
public boolean isOnLine (Vector3 other, float epsilon) {
return len2(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x) <= epsilon;
}
@Override
public boolean isOnLine (Vector3 other) {
return len2(y * other.z - z * other.y, z * other.x - x * other.z,
x * other.y - y * other.x) <= MathUtils.FLOAT_ROUNDING_ERROR;
}
@Override
public boolean isCollinear (Vector3 other, float epsilon) {
return isOnLine(other, epsilon) && hasSameDirection(other);
}
@Override
public boolean isCollinear (Vector3 other) {
return isOnLine(other) && hasSameDirection(other);
}
@Override
public boolean isCollinearOpposite (Vector3 other, float epsilon) {
return isOnLine(other, epsilon) && hasOppositeDirection(other);
}
@Override
public boolean isCollinearOpposite (Vector3 other) {
return isOnLine(other) && hasOppositeDirection(other);
}
@Override
public boolean isPerpendicular (Vector3 vector) {
return MathUtils.isZero(dot(vector));
}
@Override
public boolean isPerpendicular (Vector3 vector, float epsilon) {
return MathUtils.isZero(dot(vector), epsilon);
}
@Override
public boolean hasSameDirection (Vector3 vector) {
return dot(vector) > 0;
}
@Override
public boolean hasOppositeDirection (Vector3 vector) {
return dot(vector) < 0;
}
@Override
public Vector3 lerp (final Vector3 target, float alpha) {
x += alpha * (target.x - x);
y += alpha * (target.y - y);
z += alpha * (target.z - z);
return this;
}
@Override
public Vector3 interpolate (Vector3 target, float alpha, Interpolation interpolator) {
return lerp(target, interpolator.apply(0f, 1f, alpha));
}
/** Spherically interpolates between this vector and the target vector by alpha which is in the range [0,1]. The result is
* stored in this vector.
*
* @param target The target vector
* @param alpha The interpolation coefficient
* @return This vector for chaining. */
public Vector3 slerp (final Vector3 target, float alpha) {
final float dot = dot(target);
// If the inputs are too close for comfort, simply linearly interpolate.
if (dot > 0.9995 || dot < -0.9995) return lerp(target, alpha);
// theta0 = angle between input vectors
final float theta0 = (float)Math.acos(dot);
// theta = angle between this vector and result
final float theta = theta0 * alpha;
final float st = (float)Math.sin(theta);
final float tx = target.x - x * dot;
final float ty = target.y - y * dot;
final float tz = target.z - z * dot;
final float l2 = tx * tx + ty * ty + tz * tz;
final float dl = st * ((l2 < 0.0001f) ? 1f : 1f / (float)Math.sqrt(l2));
return scl((float)Math.cos(theta)).add(tx * dl, ty * dl, tz * dl).nor();
}
/** Converts this {@code Vector3} to a string in the format {@code (x,y,z)}.
* @return a string representation of this object. */
@Override
public String toString () {
return "(" + x + "," + y + "," + z + ")";
}
/** Sets this {@code Vector3} to the value represented by the specified string according to the format of {@link #toString()}.
* @param v the string.
* @return this vector for chaining */
public Vector3 fromString (String v) {
int s0 = v.indexOf(',', 1);
int s1 = v.indexOf(',', s0 + 1);
if (s0 != -1 && s1 != -1 && v.charAt(0) == '(' && v.charAt(v.length() - 1) == ')') {
try {
float x = Float.parseFloat(v.substring(1, s0));
float y = Float.parseFloat(v.substring(s0 + 1, s1));
float z = Float.parseFloat(v.substring(s1 + 1, v.length() - 1));
return this.set(x, y, z);
} catch (NumberFormatException ex) {
// Throw a GdxRuntimeException
}
}
throw new GdxRuntimeException("Malformed Vector3: " + v);
}
@Override
public Vector3 limit (float limit) {
return limit2(limit * limit);
}
@Override
public Vector3 limit2 (float limit2) {
float len2 = len2();
if (len2 > limit2) {
scl((float)Math.sqrt(limit2 / len2));
}
return this;
}
@Override
public Vector3 setLength (float len) {
return setLength2(len * len);
}
@Override
public Vector3 setLength2 (float len2) {
float oldLen2 = len2();
return (oldLen2 == 0 || oldLen2 == len2) ? this : scl((float)Math.sqrt(len2 / oldLen2));
}
@Override
public Vector3 clamp (float min, float max) {
final float len2 = len2();
if (len2 == 0f) return this;
float max2 = max * max;
if (len2 > max2) return scl((float)Math.sqrt(max2 / len2));
float min2 = min * min;
if (len2 < min2) return scl((float)Math.sqrt(min2 / len2));
return this;
}
@Override
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + NumberUtils.floatToIntBits(x);
result = prime * result + NumberUtils.floatToIntBits(y);
result = prime * result + NumberUtils.floatToIntBits(z);
return result;
}
@Override
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector3 other = (Vector3)obj;
if (NumberUtils.floatToIntBits(x) != NumberUtils.floatToIntBits(other.x)) return false;
if (NumberUtils.floatToIntBits(y) != NumberUtils.floatToIntBits(other.y)) return false;
if (NumberUtils.floatToIntBits(z) != NumberUtils.floatToIntBits(other.z)) return false;
return true;
}
@Override
public boolean epsilonEquals (final Vector3 other, float epsilon) {
if (other == null) return false;
if (Math.abs(other.x - x) > epsilon) return false;
if (Math.abs(other.y - y) > epsilon) return false;
if (Math.abs(other.z - z) > epsilon) return false;
return true;
}
/** Compares this vector with the other vector, using the supplied epsilon for fuzzy equality testing.
* @return whether the vectors are the same. */
public boolean epsilonEquals (float x, float y, float z, float epsilon) {
if (Math.abs(x - this.x) > epsilon) return false;
if (Math.abs(y - this.y) > epsilon) return false;
if (Math.abs(z - this.z) > epsilon) return false;
return true;
}
/** Compares this vector with the other vector using MathUtils.FLOAT_ROUNDING_ERROR for fuzzy equality testing
*
* @param other other vector to compare
* @return true if vector are equal, otherwise false */
public boolean epsilonEquals (final Vector3 other) {
return epsilonEquals(other, MathUtils.FLOAT_ROUNDING_ERROR);
}
/** Compares this vector with the other vector using MathUtils.FLOAT_ROUNDING_ERROR for fuzzy equality testing
*
* @param x x component of the other vector to compare
* @param y y component of the other vector to compare
* @param z z component of the other vector to compare
* @return true if vector are equal, otherwise false */
public boolean epsilonEquals (float x, float y, float z) {
return epsilonEquals(x, y, z, MathUtils.FLOAT_ROUNDING_ERROR);
}
@Override
public Vector3 setZero () {
this.x = 0;
this.y = 0;
this.z = 0;
return this;
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/TiledDrawableTest.java |
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.ScreenUtils;
public class TiledDrawableTest extends GdxTest {
private static final float SCALE_CHANGE = 0.25f;
private Stage stage;
private Batch batch;
private BitmapFont font;
private TextureAtlas atlas;
private TiledDrawable tiledDrawable;
@Override
public void create () {
stage = new Stage();
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/lsans-15.fnt"), false);
// Must be a texture atlas so uv is not just 0 and 1
atlas = new TextureAtlas(Gdx.files.internal("data/testAtlas.atlas"));
tiledDrawable = new TiledDrawable(atlas.findRegion("tileTester"));
Gdx.input.setInputProcessor(this);
}
@Override
public void render () {
ScreenUtils.clear(0.2f, 0.2f, 0.2f, 1);
final Batch batch = stage.getBatch();
batch.begin();
font.draw(batch,
"Scale: " + tiledDrawable.getScale() + " (to change scale press: 'A' -" + SCALE_CHANGE + ", 'D' +" + SCALE_CHANGE + ")",
8, 20);
final float leftSpacingX = 40;
final float spacingX = 80;
final float bottomSpacing = 60;
final float spacingY = 40;
float inputX = Gdx.input.getX();
float inputY = Gdx.graphics.getHeight() - Gdx.input.getY();
final float clusterWidth = Math.max(13, (inputX - leftSpacingX - (2 * spacingX)) / 3f);
final float clusterHeight = Math.max(13, (inputY - bottomSpacing - (2 * spacingY)) / 3f);
final float leftX = leftSpacingX;
final float centerX = leftSpacingX + spacingX + clusterWidth;
final float rightX = leftSpacingX + (2 * spacingX) + (2 * clusterWidth);
final float topY = bottomSpacing + (2 * spacingY) + (2 * clusterHeight);
final float centerY = bottomSpacing + spacingY + clusterHeight;
final float bottomY = bottomSpacing;
drawTiledDrawableCluster(batch, leftX, topY, clusterWidth, clusterHeight, Align.topLeft);
drawTiledDrawableCluster(batch, centerX, topY, clusterWidth, clusterHeight, Align.top);
drawTiledDrawableCluster(batch, rightX, topY, clusterWidth, clusterHeight, Align.topRight);
drawTiledDrawableCluster(batch, leftX, centerY, clusterWidth, clusterHeight, Align.left);
drawTiledDrawableCluster(batch, centerX, centerY, clusterWidth, clusterHeight, Align.center);
drawTiledDrawableCluster(batch, rightX, centerY, clusterWidth, clusterHeight, Align.right);
drawTiledDrawableCluster(batch, leftX, bottomY, clusterWidth, clusterHeight, Align.bottomLeft);
drawTiledDrawableCluster(batch, centerX, bottomY, clusterWidth, clusterHeight, Align.bottom);
drawTiledDrawableCluster(batch, rightX, bottomY, clusterWidth, clusterHeight, Align.bottomRight);
batch.end();
}
private final void drawTiledDrawableCluster (Batch batch, float x, float y, float clusterWidth, float clusterHeight,
int align) {
tiledDrawable.setAlign(align);
tiledDrawable.draw(batch, x, y, clusterWidth, clusterHeight);
font.draw(batch, Align.toString(align), x, y - 5);
}
@Override
public boolean keyDown (int keycode) {
if (keycode == Input.Keys.A) {
tiledDrawable.setScale(Math.max(SCALE_CHANGE, tiledDrawable.getScale() - SCALE_CHANGE));
} else if (keycode == Input.Keys.D) {
tiledDrawable.setScale(tiledDrawable.getScale() + SCALE_CHANGE);
}
return true;
}
@Override
public void resize (int width, int height) {
batch.getProjectionMatrix().setToOrtho2D(0, 0, width, height);
stage.getViewport().update(width, height, true);
}
@Override
public void dispose () {
stage.dispose();
font.dispose();
atlas.dispose();
}
}
|
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.ScreenUtils;
public class TiledDrawableTest extends GdxTest {
private static final float SCALE_CHANGE = 0.25f;
private Stage stage;
private Batch batch;
private BitmapFont font;
private TextureAtlas atlas;
private TiledDrawable tiledDrawable;
@Override
public void create () {
stage = new Stage();
batch = new SpriteBatch();
font = new BitmapFont(Gdx.files.internal("data/lsans-15.fnt"), false);
// Must be a texture atlas so uv is not just 0 and 1
atlas = new TextureAtlas(Gdx.files.internal("data/testAtlas.atlas"));
tiledDrawable = new TiledDrawable(atlas.findRegion("tileTester"));
Gdx.input.setInputProcessor(this);
}
@Override
public void render () {
ScreenUtils.clear(0.2f, 0.2f, 0.2f, 1);
final Batch batch = stage.getBatch();
batch.begin();
font.draw(batch,
"Scale: " + tiledDrawable.getScale() + " (to change scale press: 'A' -" + SCALE_CHANGE + ", 'D' +" + SCALE_CHANGE + ")",
8, 20);
final float leftSpacingX = 40;
final float spacingX = 80;
final float bottomSpacing = 60;
final float spacingY = 40;
float inputX = Gdx.input.getX();
float inputY = Gdx.graphics.getHeight() - Gdx.input.getY();
final float clusterWidth = Math.max(13, (inputX - leftSpacingX - (2 * spacingX)) / 3f);
final float clusterHeight = Math.max(13, (inputY - bottomSpacing - (2 * spacingY)) / 3f);
final float leftX = leftSpacingX;
final float centerX = leftSpacingX + spacingX + clusterWidth;
final float rightX = leftSpacingX + (2 * spacingX) + (2 * clusterWidth);
final float topY = bottomSpacing + (2 * spacingY) + (2 * clusterHeight);
final float centerY = bottomSpacing + spacingY + clusterHeight;
final float bottomY = bottomSpacing;
drawTiledDrawableCluster(batch, leftX, topY, clusterWidth, clusterHeight, Align.topLeft);
drawTiledDrawableCluster(batch, centerX, topY, clusterWidth, clusterHeight, Align.top);
drawTiledDrawableCluster(batch, rightX, topY, clusterWidth, clusterHeight, Align.topRight);
drawTiledDrawableCluster(batch, leftX, centerY, clusterWidth, clusterHeight, Align.left);
drawTiledDrawableCluster(batch, centerX, centerY, clusterWidth, clusterHeight, Align.center);
drawTiledDrawableCluster(batch, rightX, centerY, clusterWidth, clusterHeight, Align.right);
drawTiledDrawableCluster(batch, leftX, bottomY, clusterWidth, clusterHeight, Align.bottomLeft);
drawTiledDrawableCluster(batch, centerX, bottomY, clusterWidth, clusterHeight, Align.bottom);
drawTiledDrawableCluster(batch, rightX, bottomY, clusterWidth, clusterHeight, Align.bottomRight);
batch.end();
}
private final void drawTiledDrawableCluster (Batch batch, float x, float y, float clusterWidth, float clusterHeight,
int align) {
tiledDrawable.setAlign(align);
tiledDrawable.draw(batch, x, y, clusterWidth, clusterHeight);
font.draw(batch, Align.toString(align), x, y - 5);
}
@Override
public boolean keyDown (int keycode) {
if (keycode == Input.Keys.A) {
tiledDrawable.setScale(Math.max(SCALE_CHANGE, tiledDrawable.getScale() - SCALE_CHANGE));
} else if (keycode == Input.Keys.D) {
tiledDrawable.setScale(tiledDrawable.getScale() + SCALE_CHANGE);
}
return true;
}
@Override
public void resize (int width, int height) {
batch.getProjectionMatrix().setToOrtho2D(0, 0, width, height);
stage.getViewport().update(width, height, true);
}
@Override
public void dispose () {
stage.dispose();
font.dispose();
atlas.dispose();
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/dynamics/contacts/ContactEdge.java | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.dynamics.contacts;
import org.jbox2d.dynamics.Body;
/** A contact edge is used to connect bodies and contacts together in a contact graph where each body is a node and each contact
* is an edge. A contact edge belongs to a doubly linked list maintained in each attached body. Each contact has two contact
* nodes, one for each attached body.
*
* @author daniel */
public class ContactEdge {
/** provides quick access to the other body attached. */
public Body other = null;
/** the contact */
public Contact contact = null;
/** the previous contact edge in the body's contact list */
public ContactEdge prev = null;
/** the next contact edge in the body's contact list */
public ContactEdge next = null;
}
| /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.dynamics.contacts;
import org.jbox2d.dynamics.Body;
/** A contact edge is used to connect bodies and contacts together in a contact graph where each body is a node and each contact
* is an edge. A contact edge belongs to a doubly linked list maintained in each attached body. Each contact has two contact
* nodes, one for each attached body.
*
* @author daniel */
public class ContactEdge {
/** provides quick access to the other body attached. */
public Body other = null;
/** the contact */
public Contact contact = null;
/** the previous contact edge in the body's contact list */
public ContactEdge prev = null;
/** the next contact edge in the body's contact list */
public ContactEdge next = null;
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/particle/ParticleGroupType.java |
package org.jbox2d.particle;
public class ParticleGroupType {
/** resists penetration */
public static final int b2_solidParticleGroup = 1 << 0;
/** keeps its shape */
public static final int b2_rigidParticleGroup = 1 << 1;
}
|
package org.jbox2d.particle;
public class ParticleGroupType {
/** resists penetration */
public static final int b2_solidParticleGroup = 1 << 0;
/** keeps its shape */
public static final int b2_rigidParticleGroup = 1 << 1;
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidAudioRecorder.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** {@link AudioRecorder} implementation for the android system based on AudioRecord
* @author [email protected] */
public class AndroidAudioRecorder implements AudioRecorder {
/** the audio track we read samples from **/
private AudioRecord recorder;
@SuppressLint("MissingPermission")
public AndroidAudioRecorder (int samplingRate, boolean isMono) {
int channelConfig = isMono ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO;
int minBufferSize = AudioRecord.getMinBufferSize(samplingRate, channelConfig, AudioFormat.ENCODING_PCM_16BIT);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, samplingRate, channelConfig, AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
if (recorder.getState() != AudioRecord.STATE_INITIALIZED)
throw new GdxRuntimeException("Unable to initialize AudioRecorder.\nDo you have the RECORD_AUDIO permission?");
recorder.startRecording();
}
@Override
public void dispose () {
recorder.stop();
recorder.release();
}
@Override
public void read (short[] samples, int offset, int numSamples) {
int read = 0;
while (read != numSamples) {
read += recorder.read(samples, offset + read, numSamples - read);
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** {@link AudioRecorder} implementation for the android system based on AudioRecord
* @author [email protected] */
public class AndroidAudioRecorder implements AudioRecorder {
/** the audio track we read samples from **/
private AudioRecord recorder;
@SuppressLint("MissingPermission")
public AndroidAudioRecorder (int samplingRate, boolean isMono) {
int channelConfig = isMono ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO;
int minBufferSize = AudioRecord.getMinBufferSize(samplingRate, channelConfig, AudioFormat.ENCODING_PCM_16BIT);
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, samplingRate, channelConfig, AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
if (recorder.getState() != AudioRecord.STATE_INITIALIZED)
throw new GdxRuntimeException("Unable to initialize AudioRecorder.\nDo you have the RECORD_AUDIO permission?");
recorder.startRecording();
}
@Override
public void dispose () {
recorder.stop();
recorder.release();
}
@Override
public void read (short[] samples, int offset, int numSamples) {
int read = 0;
while (read != numSamples) {
read += recorder.read(samples, offset + read, numSamples - read);
}
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests-android/assets/data/g3d/shapes/cube_1.5x1.5.g3dj | {
"version": [ 0, 1],
"id": "",
"meshes": [
{
"attributes": ["POSITION", "NORMAL", "TANGENT", "BINORMAL", "TEXCOORD0"],
"vertices": [
5.000000, 5.000000, 5.000000, 0.000000, 0.000000, 1.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.500000, -0.500000,
-5.000000, 5.000000, 5.000000, 0.000000, 0.000000, 1.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.500000,
-5.000000, -5.000000, 5.000000, 0.000000, 0.000000, 1.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 1.000000,
5.000000, -5.000000, 5.000000, 0.000000, 0.000000, 1.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.500000, 1.000000,
5.000000, 5.000000, 5.000000, 0.000000, 1.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 1.500000, 1.000000,
5.000000, 5.000000, -5.000000, 0.000000, 1.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 1.500000, -0.500000,
-5.000000, 5.000000, 5.000000, 0.000000, 1.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 1.000000,
-5.000000, 5.000000, -5.000000, 0.000000, 1.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, -0.500000,
5.000000, -5.000000, -5.000000, 0.000000, 0.000000, -1.000000, -1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 1.000000,
-5.000000, -5.000000, -5.000000, 0.000000, 0.000000, -1.000000, -1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.500000, 1.000000,
-5.000000, 5.000000, -5.000000, 0.000000, 0.000000, -1.000000, -1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.500000, -0.500000,
5.000000, 5.000000, -5.000000, 0.000000, 0.000000, -1.000000, -1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.500000,
5.000000, -5.000000, 5.000000, 0.000000, -1.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.000000, 0.000000, 1.000000, 1.500000, -0.500000,
-5.000000, -5.000000, 5.000000, 0.000000, -1.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.000000, 0.000000, 1.000000, 0.000000, -0.500000,
-5.000000, -5.000000, -5.000000, 0.000000, -1.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.000000, 0.000000, 1.000000, 0.000000, 1.000000,
5.000000, -5.000000, -5.000000, 0.000000, -1.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.000000, 0.000000, 1.000000, 1.500000, 1.000000,
5.000000, 5.000000, 5.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, 0.000000, 0.000000, -0.500000,
5.000000, -5.000000, 5.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, 0.000000, 0.000000, 1.000000,
5.000000, 5.000000, -5.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, 0.000000, 1.500000, -0.500000,
5.000000, -5.000000, -5.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, 0.000000, 1.500000, 1.000000,
-5.000000, 5.000000, 5.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.000000, -0.000000, 1.500000, -0.500000,
-5.000000, -5.000000, -5.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.000000, -0.000000, 0.000000, 1.000000,
-5.000000, -5.000000, 5.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.000000, -0.000000, 1.500000, 1.000000,
-5.000000, 5.000000, -5.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.000000, -0.000000, 0.000000, -0.500000
],
"parts": [
{
"id": "shape1_part1",
"type": "TRIANGLES",
"indices": [
0, 1, 2, 0, 2, 3, 4, 5, 6, 6, 5, 7,
8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15,
16, 17, 18, 17, 19, 18, 20, 21, 22, 21, 20, 23
]
}
]
}
],
"materials": [
{
"id": "chesterField_phong",
"diffuse": [ 1.000000, 1.000000, 1.000000],
"specular": [ 0.500000, 0.500000, 0.500000]
}
],
"nodes": [
{
"id": "pCube1",
"parts": [
{
"meshpartid": "shape1_part1",
"materialid": "chesterField_phong",
"uvMapping": [[ 0, 1, 2]]
}
]
}
],
"animations": []
} | {
"version": [ 0, 1],
"id": "",
"meshes": [
{
"attributes": ["POSITION", "NORMAL", "TANGENT", "BINORMAL", "TEXCOORD0"],
"vertices": [
5.000000, 5.000000, 5.000000, 0.000000, 0.000000, 1.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.500000, -0.500000,
-5.000000, 5.000000, 5.000000, 0.000000, 0.000000, 1.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.500000,
-5.000000, -5.000000, 5.000000, 0.000000, 0.000000, 1.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 1.000000,
5.000000, -5.000000, 5.000000, 0.000000, 0.000000, 1.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.500000, 1.000000,
5.000000, 5.000000, 5.000000, 0.000000, 1.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 1.500000, 1.000000,
5.000000, 5.000000, -5.000000, 0.000000, 1.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 1.500000, -0.500000,
-5.000000, 5.000000, 5.000000, 0.000000, 1.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, 1.000000,
-5.000000, 5.000000, -5.000000, 0.000000, 1.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, 0.000000, -0.500000,
5.000000, -5.000000, -5.000000, 0.000000, 0.000000, -1.000000, -1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 1.000000,
-5.000000, -5.000000, -5.000000, 0.000000, 0.000000, -1.000000, -1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.500000, 1.000000,
-5.000000, 5.000000, -5.000000, 0.000000, 0.000000, -1.000000, -1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.500000, -0.500000,
5.000000, 5.000000, -5.000000, 0.000000, 0.000000, -1.000000, -1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.500000,
5.000000, -5.000000, 5.000000, 0.000000, -1.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.000000, 0.000000, 1.000000, 1.500000, -0.500000,
-5.000000, -5.000000, 5.000000, 0.000000, -1.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.000000, 0.000000, 1.000000, 0.000000, -0.500000,
-5.000000, -5.000000, -5.000000, 0.000000, -1.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.000000, 0.000000, 1.000000, 0.000000, 1.000000,
5.000000, -5.000000, -5.000000, 0.000000, -1.000000, 0.000000, 1.000000, 0.000000, 0.000000, -0.000000, 0.000000, 1.000000, 1.500000, 1.000000,
5.000000, 5.000000, 5.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, 0.000000, 0.000000, -0.500000,
5.000000, -5.000000, 5.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, 0.000000, 0.000000, 1.000000,
5.000000, 5.000000, -5.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, 0.000000, 1.500000, -0.500000,
5.000000, -5.000000, -5.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, -1.000000, -0.000000, 1.000000, 0.000000, 1.500000, 1.000000,
-5.000000, 5.000000, 5.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.000000, -0.000000, 1.500000, -0.500000,
-5.000000, -5.000000, -5.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.000000, -0.000000, 0.000000, 1.000000,
-5.000000, -5.000000, 5.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.000000, -0.000000, 1.500000, 1.000000,
-5.000000, 5.000000, -5.000000, -1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 1.000000, -0.000000, 0.000000, -0.500000
],
"parts": [
{
"id": "shape1_part1",
"type": "TRIANGLES",
"indices": [
0, 1, 2, 0, 2, 3, 4, 5, 6, 6, 5, 7,
8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15,
16, 17, 18, 17, 19, 18, 20, 21, 22, 21, 20, 23
]
}
]
}
],
"materials": [
{
"id": "chesterField_phong",
"diffuse": [ 1.000000, 1.000000, 1.000000],
"specular": [ 0.500000, 0.500000, 0.500000]
}
],
"nodes": [
{
"id": "pCube1",
"parts": [
{
"meshpartid": "shape1_part1",
"materialid": "chesterField_phong",
"uvMapping": [[ 0, 1, 2]]
}
]
}
],
"animations": []
} | -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./gdx/src/com/badlogic/gdx/graphics/Pixmap.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.Gdx2DPixmap;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* <p>
* A Pixmap represents an image in memory. It has a width and height expressed in pixels as well as a {@link Format} specifying
* the number and order of color components per pixel. Coordinates of pixels are specified with respect to the top left corner of
* the image, with the x-axis pointing to the right and the y-axis pointing downwards.
* <p>
* By default all methods use blending. You can disable blending with {@link Pixmap#setBlending(Blending)}, which may reduce
* blitting time by ~30%. The {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)} method will scale and
* stretch the source image to a target image. There either nearest neighbour or bilinear filtering can be used.
* <p>
* A Pixmap stores its data in native heap memory. It is mandatory to call {@link Pixmap#dispose()} when the pixmap is no longer
* needed, otherwise memory leaks will result
* @author [email protected] */
public class Pixmap implements Disposable {
/** Different pixel formats.
*
* @author mzechner */
public enum Format {
Alpha, Intensity, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888;
public static int toGdx2DPixmapFormat (Format format) {
if (format == Alpha) return Gdx2DPixmap.GDX2D_FORMAT_ALPHA;
if (format == Intensity) return Gdx2DPixmap.GDX2D_FORMAT_ALPHA;
if (format == LuminanceAlpha) return Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA;
if (format == RGB565) return Gdx2DPixmap.GDX2D_FORMAT_RGB565;
if (format == RGBA4444) return Gdx2DPixmap.GDX2D_FORMAT_RGBA4444;
if (format == RGB888) return Gdx2DPixmap.GDX2D_FORMAT_RGB888;
if (format == RGBA8888) return Gdx2DPixmap.GDX2D_FORMAT_RGBA8888;
throw new GdxRuntimeException("Unknown Format: " + format);
}
public static Format fromGdx2DPixmapFormat (int format) {
if (format == Gdx2DPixmap.GDX2D_FORMAT_ALPHA) return Alpha;
if (format == Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA) return LuminanceAlpha;
if (format == Gdx2DPixmap.GDX2D_FORMAT_RGB565) return RGB565;
if (format == Gdx2DPixmap.GDX2D_FORMAT_RGBA4444) return RGBA4444;
if (format == Gdx2DPixmap.GDX2D_FORMAT_RGB888) return RGB888;
if (format == Gdx2DPixmap.GDX2D_FORMAT_RGBA8888) return RGBA8888;
throw new GdxRuntimeException("Unknown Gdx2DPixmap Format: " + format);
}
public static int toGlFormat (Format format) {
return Gdx2DPixmap.toGlFormat(toGdx2DPixmapFormat(format));
}
public static int toGlType (Format format) {
return Gdx2DPixmap.toGlType(toGdx2DPixmapFormat(format));
}
}
/** Blending functions to be set with {@link Pixmap#setBlending}.
* @author mzechner */
public enum Blending {
None, SourceOver
}
/** Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
*
* @author mzechner */
public enum Filter {
NearestNeighbour, BiLinear
}
/** Creates a Pixmap from a part of the current framebuffer.
* @param x framebuffer region x
* @param y framebuffer region y
* @param w framebuffer region width
* @param h framebuffer region height
* @return the pixmap */
public static Pixmap createFromFrameBuffer (int x, int y, int w, int h) {
Gdx.gl.glPixelStorei(GL20.GL_PACK_ALIGNMENT, 1);
final Pixmap pixmap = new Pixmap(w, h, Format.RGBA8888);
ByteBuffer pixels = pixmap.getPixels();
Gdx.gl.glReadPixels(x, y, w, h, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixels);
return pixmap;
}
private Blending blending = Blending.SourceOver;
private Filter filter = Filter.BiLinear;
final Gdx2DPixmap pixmap;
int color = 0;
private boolean disposed;
/** Sets the type of {@link Blending} to be used for all operations. Default is {@link Blending#SourceOver}.
* @param blending the blending type */
public void setBlending (Blending blending) {
this.blending = blending;
pixmap.setBlend(blending == Blending.None ? 0 : 1);
}
/** Sets the type of interpolation {@link Filter} to be used in conjunction with
* {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
* @param filter the filter. */
public void setFilter (Filter filter) {
this.filter = filter;
pixmap.setScale(filter == Filter.NearestNeighbour ? Gdx2DPixmap.GDX2D_SCALE_NEAREST : Gdx2DPixmap.GDX2D_SCALE_LINEAR);
}
/** Creates a new Pixmap instance with the given width, height and format.
* @param width the width in pixels
* @param height the height in pixels
* @param format the {@link Format} */
public Pixmap (int width, int height, Format format) {
pixmap = new Gdx2DPixmap(width, height, Format.toGdx2DPixmapFormat(format));
setColor(0, 0, 0, 0);
fill();
}
/** Creates a new Pixmap instance from the given encoded image data. The image can be encoded as JPEG, PNG or BMP. Not
* available on GWT backend.
*
* @param encodedData the encoded image data
* @param offset the offset
* @param len the length */
public Pixmap (byte[] encodedData, int offset, int len) {
try {
pixmap = new Gdx2DPixmap(encodedData, offset, len, 0);
} catch (IOException e) {
throw new GdxRuntimeException("Couldn't load pixmap from image data", e);
}
}
/** Creates a new Pixmap instance from the given encoded image data. The image can be encoded as JPEG, PNG or BMP. Not
* available on GWT backend.
*
* @param encodedData the encoded image data
* @param offset the offset relative to the base address of encodedData
* @param len the length */
public Pixmap (ByteBuffer encodedData, int offset, int len) {
if (!encodedData.isDirect()) throw new GdxRuntimeException("Couldn't load pixmap from non-direct ByteBuffer");
try {
pixmap = new Gdx2DPixmap(encodedData, offset, len, 0);
} catch (IOException e) {
throw new GdxRuntimeException("Couldn't load pixmap from image data", e);
}
}
/** Creates a new Pixmap instance from the given encoded image data. The image can be encoded as JPEG, PNG or BMP. Not
* available on GWT backend.
*
* Offset is based on the position of the buffer. Length is based on the remaining bytes of the buffer.
*
* @param encodedData the encoded image data */
public Pixmap (ByteBuffer encodedData) {
this(encodedData, encodedData.position(), encodedData.remaining());
}
/** Creates a new Pixmap instance from the given file. The file must be a Png, Jpeg or Bitmap. Paletted formats are not
* supported.
*
* @param file the {@link FileHandle} */
public Pixmap (FileHandle file) {
try {
byte[] bytes = file.readBytes();
pixmap = new Gdx2DPixmap(bytes, 0, bytes.length, 0);
} catch (Exception e) {
throw new GdxRuntimeException("Couldn't load file: " + file, e);
}
}
/** Constructs a new Pixmap from a {@link Gdx2DPixmap}.
* @param pixmap */
public Pixmap (Gdx2DPixmap pixmap) {
this.pixmap = pixmap;
}
/** Downloads an image from http(s) url and passes it as a {@link Pixmap} to the specified
* {@link DownloadPixmapResponseListener}
*
* @param url http url to download the image from
* @param responseListener the listener to call once the image is available as a {@link Pixmap} */
public static void downloadFromUrl (String url, final DownloadPixmapResponseListener responseListener) {
Net.HttpRequest request = new Net.HttpRequest(Net.HttpMethods.GET);
request.setUrl(url);
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse (Net.HttpResponse httpResponse) {
final byte[] result = httpResponse.getResult();
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
try {
Pixmap pixmap = new Pixmap(result, 0, result.length);
responseListener.downloadComplete(pixmap);
} catch (Throwable t) {
failed(t);
}
}
});
}
@Override
public void failed (Throwable t) {
responseListener.downloadFailed(t);
}
@Override
public void cancelled () {
// no way to cancel, will never get called
}
});
}
/** Sets the color for the following drawing operations
* @param color the color, encoded as RGBA8888 */
public void setColor (int color) {
this.color = color;
}
/** Sets the color for the following drawing operations.
*
* @param r The red component.
* @param g The green component.
* @param b The blue component.
* @param a The alpha component. */
public void setColor (float r, float g, float b, float a) {
color = Color.rgba8888(r, g, b, a);
}
/** Sets the color for the following drawing operations.
* @param color The color. */
public void setColor (Color color) {
this.color = Color.rgba8888(color.r, color.g, color.b, color.a);
}
/** Fills the complete bitmap with the currently set color. */
public void fill () {
pixmap.clear(color);
}
// /**
// * Sets the width in pixels of strokes.
// *
// * @param width The stroke width in pixels.
// */
// public void setStrokeWidth (int width);
/** Draws a line between the given coordinates using the currently set color.
*
* @param x The x-coodinate of the first point
* @param y The y-coordinate of the first point
* @param x2 The x-coordinate of the first point
* @param y2 The y-coordinate of the first point */
public void drawLine (int x, int y, int x2, int y2) {
pixmap.drawLine(x, y, x2, y2, color);
}
/** Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points
* downwards) using the current color.
*
* @param x The x coordinate
* @param y The y coordinate
* @param width The width in pixels
* @param height The height in pixels */
public void drawRectangle (int x, int y, int width, int height) {
pixmap.drawRect(x, y, width, height, color);
}
/** Draws an area from another Pixmap to this Pixmap.
*
* @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner) */
public void drawPixmap (Pixmap pixmap, int x, int y) {
drawPixmap(pixmap, x, y, 0, 0, pixmap.getWidth(), pixmap.getHeight());
}
/** Draws an area from another Pixmap to this Pixmap.
*
* @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner)
* @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area from the other Pixmap in pixels
* @param srcHeight The height of the area from the other Pixmap in pixels */
public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) {
this.pixmap.drawPixmap(pixmap.pixmap, srcx, srcy, x, y, srcWidth, srcHeight);
}
/** Draws an area from another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the
* specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest
* neighbour or bilinear).
*
* @param pixmap The other Pixmap
* @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area from the other Pixmap in pixels
* @param srcHeight The height of the area from the other Pixmap in pixels
* @param dstx The target x-coordinate (top left corner)
* @param dsty The target y-coordinate (top left corner)
* @param dstWidth The target width
* @param dstHeight the target height */
public void drawPixmap (Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth,
int dstHeight) {
this.pixmap.drawPixmap(pixmap.pixmap, srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight);
}
/** Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using
* the current color.
*
* @param x The x coordinate
* @param y The y coordinate
* @param width The width in pixels
* @param height The height in pixels */
public void fillRectangle (int x, int y, int width, int height) {
pixmap.fillRect(x, y, width, height, color);
}
/** Draws a circle outline with the center at x,y and a radius using the current color and stroke width.
*
* @param x The x-coordinate of the center
* @param y The y-coordinate of the center
* @param radius The radius in pixels */
public void drawCircle (int x, int y, int radius) {
pixmap.drawCircle(x, y, radius, color);
}
/** Fills a circle with the center at x,y and a radius using the current color.
*
* @param x The x-coordinate of the center
* @param y The y-coordinate of the center
* @param radius The radius in pixels */
public void fillCircle (int x, int y, int radius) {
pixmap.fillCircle(x, y, radius, color);
}
/** Fills a triangle with vertices at x1,y1 and x2,y2 and x3,y3 using the current color.
*
* @param x1 The x-coordinate of vertex 1
* @param y1 The y-coordinate of vertex 1
* @param x2 The x-coordinate of vertex 2
* @param y2 The y-coordinate of vertex 2
* @param x3 The x-coordinate of vertex 3
* @param y3 The y-coordinate of vertex 3 */
public void fillTriangle (int x1, int y1, int x2, int y2, int x3, int y3) {
pixmap.fillTriangle(x1, y1, x2, y2, x3, y3, color);
}
/** Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one.
*
* @param x The x-coordinate
* @param y The y-coordinate
* @return The pixel color in RGBA8888 format. */
public int getPixel (int x, int y) {
return pixmap.getPixel(x, y);
}
/** @return The width of the Pixmap in pixels. */
public int getWidth () {
return pixmap.getWidth();
}
/** @return The height of the Pixmap in pixels. */
public int getHeight () {
return pixmap.getHeight();
}
/** Releases all resources associated with this Pixmap. */
public void dispose () {
if (disposed) throw new GdxRuntimeException("Pixmap already disposed!");
pixmap.dispose();
disposed = true;
}
public boolean isDisposed () {
return disposed;
}
/** Draws a pixel at the given location with the current color.
*
* @param x the x-coordinate
* @param y the y-coordinate */
public void drawPixel (int x, int y) {
pixmap.setPixel(x, y, color);
}
/** Draws a pixel at the given location with the given color.
*
* @param x the x-coordinate
* @param y the y-coordinate
* @param color the color in RGBA8888 format. */
public void drawPixel (int x, int y, int color) {
pixmap.setPixel(x, y, color);
}
/** Returns the OpenGL ES format of this Pixmap. Used as the seventh parameter to
* {@link GL20#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}.
* @return one of GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. */
public int getGLFormat () {
return pixmap.getGLFormat();
}
/** Returns the OpenGL ES format of this Pixmap. Used as the third parameter to
* {@link GL20#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}.
* @return one of GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. */
public int getGLInternalFormat () {
return pixmap.getGLInternalFormat();
}
/** Returns the OpenGL ES type of this Pixmap. Used as the eighth parameter to
* {@link GL20#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}.
* @return one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4 */
public int getGLType () {
return pixmap.getGLType();
}
/** Returns the direct ByteBuffer holding the pixel data. For the format Alpha each value is encoded as a byte. For the format
* LuminanceAlpha the luminance is the first byte and the alpha is the second byte of the pixel. For the formats RGB888 and
* RGBA8888 the color components are stored in a single byte each in the order red, green, blue (alpha). For the formats RGB565
* and RGBA4444 the pixel colors are stored in shorts in machine dependent order.
* @return the direct {@link ByteBuffer} holding the pixel data. */
public ByteBuffer getPixels () {
if (disposed) throw new GdxRuntimeException("Pixmap already disposed");
return pixmap.getPixels();
}
/** Sets pixels from a provided direct byte buffer.
* @param pixels Pixels to copy from, should be a direct ByteBuffer and match Pixmap data size (see {@link #getPixels()}). */
public void setPixels (ByteBuffer pixels) {
if (!pixels.isDirect()) throw new GdxRuntimeException("Couldn't setPixels from non-direct ByteBuffer");
ByteBuffer dst = pixmap.getPixels();
BufferUtils.copy(pixels, dst, dst.limit());
}
/** @return the {@link Format} of this Pixmap. */
public Format getFormat () {
return Format.fromGdx2DPixmapFormat(pixmap.getFormat());
}
/** @return the currently set {@link Blending} */
public Blending getBlending () {
return blending;
}
/** @return the currently set {@link Filter} */
public Filter getFilter () {
return filter;
}
/** Response listener for {@link #downloadFromUrl(String, DownloadPixmapResponseListener)} */
public interface DownloadPixmapResponseListener {
/** Called on the render thread when image was downloaded successfully.
* @param pixmap */
void downloadComplete (Pixmap pixmap);
/** Called when image download failed. This might get called on a background thread. */
void downloadFailed (Throwable t);
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.Gdx2DPixmap;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* <p>
* A Pixmap represents an image in memory. It has a width and height expressed in pixels as well as a {@link Format} specifying
* the number and order of color components per pixel. Coordinates of pixels are specified with respect to the top left corner of
* the image, with the x-axis pointing to the right and the y-axis pointing downwards.
* <p>
* By default all methods use blending. You can disable blending with {@link Pixmap#setBlending(Blending)}, which may reduce
* blitting time by ~30%. The {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)} method will scale and
* stretch the source image to a target image. There either nearest neighbour or bilinear filtering can be used.
* <p>
* A Pixmap stores its data in native heap memory. It is mandatory to call {@link Pixmap#dispose()} when the pixmap is no longer
* needed, otherwise memory leaks will result
* @author [email protected] */
public class Pixmap implements Disposable {
/** Different pixel formats.
*
* @author mzechner */
public enum Format {
Alpha, Intensity, LuminanceAlpha, RGB565, RGBA4444, RGB888, RGBA8888;
public static int toGdx2DPixmapFormat (Format format) {
if (format == Alpha) return Gdx2DPixmap.GDX2D_FORMAT_ALPHA;
if (format == Intensity) return Gdx2DPixmap.GDX2D_FORMAT_ALPHA;
if (format == LuminanceAlpha) return Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA;
if (format == RGB565) return Gdx2DPixmap.GDX2D_FORMAT_RGB565;
if (format == RGBA4444) return Gdx2DPixmap.GDX2D_FORMAT_RGBA4444;
if (format == RGB888) return Gdx2DPixmap.GDX2D_FORMAT_RGB888;
if (format == RGBA8888) return Gdx2DPixmap.GDX2D_FORMAT_RGBA8888;
throw new GdxRuntimeException("Unknown Format: " + format);
}
public static Format fromGdx2DPixmapFormat (int format) {
if (format == Gdx2DPixmap.GDX2D_FORMAT_ALPHA) return Alpha;
if (format == Gdx2DPixmap.GDX2D_FORMAT_LUMINANCE_ALPHA) return LuminanceAlpha;
if (format == Gdx2DPixmap.GDX2D_FORMAT_RGB565) return RGB565;
if (format == Gdx2DPixmap.GDX2D_FORMAT_RGBA4444) return RGBA4444;
if (format == Gdx2DPixmap.GDX2D_FORMAT_RGB888) return RGB888;
if (format == Gdx2DPixmap.GDX2D_FORMAT_RGBA8888) return RGBA8888;
throw new GdxRuntimeException("Unknown Gdx2DPixmap Format: " + format);
}
public static int toGlFormat (Format format) {
return Gdx2DPixmap.toGlFormat(toGdx2DPixmapFormat(format));
}
public static int toGlType (Format format) {
return Gdx2DPixmap.toGlType(toGdx2DPixmapFormat(format));
}
}
/** Blending functions to be set with {@link Pixmap#setBlending}.
* @author mzechner */
public enum Blending {
None, SourceOver
}
/** Filters to be used with {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
*
* @author mzechner */
public enum Filter {
NearestNeighbour, BiLinear
}
/** Creates a Pixmap from a part of the current framebuffer.
* @param x framebuffer region x
* @param y framebuffer region y
* @param w framebuffer region width
* @param h framebuffer region height
* @return the pixmap */
public static Pixmap createFromFrameBuffer (int x, int y, int w, int h) {
Gdx.gl.glPixelStorei(GL20.GL_PACK_ALIGNMENT, 1);
final Pixmap pixmap = new Pixmap(w, h, Format.RGBA8888);
ByteBuffer pixels = pixmap.getPixels();
Gdx.gl.glReadPixels(x, y, w, h, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixels);
return pixmap;
}
private Blending blending = Blending.SourceOver;
private Filter filter = Filter.BiLinear;
final Gdx2DPixmap pixmap;
int color = 0;
private boolean disposed;
/** Sets the type of {@link Blending} to be used for all operations. Default is {@link Blending#SourceOver}.
* @param blending the blending type */
public void setBlending (Blending blending) {
this.blending = blending;
pixmap.setBlend(blending == Blending.None ? 0 : 1);
}
/** Sets the type of interpolation {@link Filter} to be used in conjunction with
* {@link Pixmap#drawPixmap(Pixmap, int, int, int, int, int, int, int, int)}.
* @param filter the filter. */
public void setFilter (Filter filter) {
this.filter = filter;
pixmap.setScale(filter == Filter.NearestNeighbour ? Gdx2DPixmap.GDX2D_SCALE_NEAREST : Gdx2DPixmap.GDX2D_SCALE_LINEAR);
}
/** Creates a new Pixmap instance with the given width, height and format.
* @param width the width in pixels
* @param height the height in pixels
* @param format the {@link Format} */
public Pixmap (int width, int height, Format format) {
pixmap = new Gdx2DPixmap(width, height, Format.toGdx2DPixmapFormat(format));
setColor(0, 0, 0, 0);
fill();
}
/** Creates a new Pixmap instance from the given encoded image data. The image can be encoded as JPEG, PNG or BMP. Not
* available on GWT backend.
*
* @param encodedData the encoded image data
* @param offset the offset
* @param len the length */
public Pixmap (byte[] encodedData, int offset, int len) {
try {
pixmap = new Gdx2DPixmap(encodedData, offset, len, 0);
} catch (IOException e) {
throw new GdxRuntimeException("Couldn't load pixmap from image data", e);
}
}
/** Creates a new Pixmap instance from the given encoded image data. The image can be encoded as JPEG, PNG or BMP. Not
* available on GWT backend.
*
* @param encodedData the encoded image data
* @param offset the offset relative to the base address of encodedData
* @param len the length */
public Pixmap (ByteBuffer encodedData, int offset, int len) {
if (!encodedData.isDirect()) throw new GdxRuntimeException("Couldn't load pixmap from non-direct ByteBuffer");
try {
pixmap = new Gdx2DPixmap(encodedData, offset, len, 0);
} catch (IOException e) {
throw new GdxRuntimeException("Couldn't load pixmap from image data", e);
}
}
/** Creates a new Pixmap instance from the given encoded image data. The image can be encoded as JPEG, PNG or BMP. Not
* available on GWT backend.
*
* Offset is based on the position of the buffer. Length is based on the remaining bytes of the buffer.
*
* @param encodedData the encoded image data */
public Pixmap (ByteBuffer encodedData) {
this(encodedData, encodedData.position(), encodedData.remaining());
}
/** Creates a new Pixmap instance from the given file. The file must be a Png, Jpeg or Bitmap. Paletted formats are not
* supported.
*
* @param file the {@link FileHandle} */
public Pixmap (FileHandle file) {
try {
byte[] bytes = file.readBytes();
pixmap = new Gdx2DPixmap(bytes, 0, bytes.length, 0);
} catch (Exception e) {
throw new GdxRuntimeException("Couldn't load file: " + file, e);
}
}
/** Constructs a new Pixmap from a {@link Gdx2DPixmap}.
* @param pixmap */
public Pixmap (Gdx2DPixmap pixmap) {
this.pixmap = pixmap;
}
/** Downloads an image from http(s) url and passes it as a {@link Pixmap} to the specified
* {@link DownloadPixmapResponseListener}
*
* @param url http url to download the image from
* @param responseListener the listener to call once the image is available as a {@link Pixmap} */
public static void downloadFromUrl (String url, final DownloadPixmapResponseListener responseListener) {
Net.HttpRequest request = new Net.HttpRequest(Net.HttpMethods.GET);
request.setUrl(url);
Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse (Net.HttpResponse httpResponse) {
final byte[] result = httpResponse.getResult();
Gdx.app.postRunnable(new Runnable() {
@Override
public void run () {
try {
Pixmap pixmap = new Pixmap(result, 0, result.length);
responseListener.downloadComplete(pixmap);
} catch (Throwable t) {
failed(t);
}
}
});
}
@Override
public void failed (Throwable t) {
responseListener.downloadFailed(t);
}
@Override
public void cancelled () {
// no way to cancel, will never get called
}
});
}
/** Sets the color for the following drawing operations
* @param color the color, encoded as RGBA8888 */
public void setColor (int color) {
this.color = color;
}
/** Sets the color for the following drawing operations.
*
* @param r The red component.
* @param g The green component.
* @param b The blue component.
* @param a The alpha component. */
public void setColor (float r, float g, float b, float a) {
color = Color.rgba8888(r, g, b, a);
}
/** Sets the color for the following drawing operations.
* @param color The color. */
public void setColor (Color color) {
this.color = Color.rgba8888(color.r, color.g, color.b, color.a);
}
/** Fills the complete bitmap with the currently set color. */
public void fill () {
pixmap.clear(color);
}
// /**
// * Sets the width in pixels of strokes.
// *
// * @param width The stroke width in pixels.
// */
// public void setStrokeWidth (int width);
/** Draws a line between the given coordinates using the currently set color.
*
* @param x The x-coodinate of the first point
* @param y The y-coordinate of the first point
* @param x2 The x-coordinate of the first point
* @param y2 The y-coordinate of the first point */
public void drawLine (int x, int y, int x2, int y2) {
pixmap.drawLine(x, y, x2, y2, color);
}
/** Draws a rectangle outline starting at x, y extending by width to the right and by height downwards (y-axis points
* downwards) using the current color.
*
* @param x The x coordinate
* @param y The y coordinate
* @param width The width in pixels
* @param height The height in pixels */
public void drawRectangle (int x, int y, int width, int height) {
pixmap.drawRect(x, y, width, height, color);
}
/** Draws an area from another Pixmap to this Pixmap.
*
* @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner) */
public void drawPixmap (Pixmap pixmap, int x, int y) {
drawPixmap(pixmap, x, y, 0, 0, pixmap.getWidth(), pixmap.getHeight());
}
/** Draws an area from another Pixmap to this Pixmap.
*
* @param pixmap The other Pixmap
* @param x The target x-coordinate (top left corner)
* @param y The target y-coordinate (top left corner)
* @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area from the other Pixmap in pixels
* @param srcHeight The height of the area from the other Pixmap in pixels */
public void drawPixmap (Pixmap pixmap, int x, int y, int srcx, int srcy, int srcWidth, int srcHeight) {
this.pixmap.drawPixmap(pixmap.pixmap, srcx, srcy, x, y, srcWidth, srcHeight);
}
/** Draws an area from another Pixmap to this Pixmap. This will automatically scale and stretch the source image to the
* specified target rectangle. Use {@link Pixmap#setFilter(Filter)} to specify the type of filtering to be used (nearest
* neighbour or bilinear).
*
* @param pixmap The other Pixmap
* @param srcx The source x-coordinate (top left corner)
* @param srcy The source y-coordinate (top left corner);
* @param srcWidth The width of the area from the other Pixmap in pixels
* @param srcHeight The height of the area from the other Pixmap in pixels
* @param dstx The target x-coordinate (top left corner)
* @param dsty The target y-coordinate (top left corner)
* @param dstWidth The target width
* @param dstHeight the target height */
public void drawPixmap (Pixmap pixmap, int srcx, int srcy, int srcWidth, int srcHeight, int dstx, int dsty, int dstWidth,
int dstHeight) {
this.pixmap.drawPixmap(pixmap.pixmap, srcx, srcy, srcWidth, srcHeight, dstx, dsty, dstWidth, dstHeight);
}
/** Fills a rectangle starting at x, y extending by width to the right and by height downwards (y-axis points downwards) using
* the current color.
*
* @param x The x coordinate
* @param y The y coordinate
* @param width The width in pixels
* @param height The height in pixels */
public void fillRectangle (int x, int y, int width, int height) {
pixmap.fillRect(x, y, width, height, color);
}
/** Draws a circle outline with the center at x,y and a radius using the current color and stroke width.
*
* @param x The x-coordinate of the center
* @param y The y-coordinate of the center
* @param radius The radius in pixels */
public void drawCircle (int x, int y, int radius) {
pixmap.drawCircle(x, y, radius, color);
}
/** Fills a circle with the center at x,y and a radius using the current color.
*
* @param x The x-coordinate of the center
* @param y The y-coordinate of the center
* @param radius The radius in pixels */
public void fillCircle (int x, int y, int radius) {
pixmap.fillCircle(x, y, radius, color);
}
/** Fills a triangle with vertices at x1,y1 and x2,y2 and x3,y3 using the current color.
*
* @param x1 The x-coordinate of vertex 1
* @param y1 The y-coordinate of vertex 1
* @param x2 The x-coordinate of vertex 2
* @param y2 The y-coordinate of vertex 2
* @param x3 The x-coordinate of vertex 3
* @param y3 The y-coordinate of vertex 3 */
public void fillTriangle (int x1, int y1, int x2, int y2, int x3, int y3) {
pixmap.fillTriangle(x1, y1, x2, y2, x3, y3, color);
}
/** Returns the 32-bit RGBA8888 value of the pixel at x, y. For Alpha formats the RGB components will be one.
*
* @param x The x-coordinate
* @param y The y-coordinate
* @return The pixel color in RGBA8888 format. */
public int getPixel (int x, int y) {
return pixmap.getPixel(x, y);
}
/** @return The width of the Pixmap in pixels. */
public int getWidth () {
return pixmap.getWidth();
}
/** @return The height of the Pixmap in pixels. */
public int getHeight () {
return pixmap.getHeight();
}
/** Releases all resources associated with this Pixmap. */
public void dispose () {
if (disposed) throw new GdxRuntimeException("Pixmap already disposed!");
pixmap.dispose();
disposed = true;
}
public boolean isDisposed () {
return disposed;
}
/** Draws a pixel at the given location with the current color.
*
* @param x the x-coordinate
* @param y the y-coordinate */
public void drawPixel (int x, int y) {
pixmap.setPixel(x, y, color);
}
/** Draws a pixel at the given location with the given color.
*
* @param x the x-coordinate
* @param y the y-coordinate
* @param color the color in RGBA8888 format. */
public void drawPixel (int x, int y, int color) {
pixmap.setPixel(x, y, color);
}
/** Returns the OpenGL ES format of this Pixmap. Used as the seventh parameter to
* {@link GL20#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}.
* @return one of GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. */
public int getGLFormat () {
return pixmap.getGLFormat();
}
/** Returns the OpenGL ES format of this Pixmap. Used as the third parameter to
* {@link GL20#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}.
* @return one of GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. */
public int getGLInternalFormat () {
return pixmap.getGLInternalFormat();
}
/** Returns the OpenGL ES type of this Pixmap. Used as the eighth parameter to
* {@link GL20#glTexImage2D(int, int, int, int, int, int, int, int, java.nio.Buffer)}.
* @return one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_4_4_4_4 */
public int getGLType () {
return pixmap.getGLType();
}
/** Returns the direct ByteBuffer holding the pixel data. For the format Alpha each value is encoded as a byte. For the format
* LuminanceAlpha the luminance is the first byte and the alpha is the second byte of the pixel. For the formats RGB888 and
* RGBA8888 the color components are stored in a single byte each in the order red, green, blue (alpha). For the formats RGB565
* and RGBA4444 the pixel colors are stored in shorts in machine dependent order.
* @return the direct {@link ByteBuffer} holding the pixel data. */
public ByteBuffer getPixels () {
if (disposed) throw new GdxRuntimeException("Pixmap already disposed");
return pixmap.getPixels();
}
/** Sets pixels from a provided direct byte buffer.
* @param pixels Pixels to copy from, should be a direct ByteBuffer and match Pixmap data size (see {@link #getPixels()}). */
public void setPixels (ByteBuffer pixels) {
if (!pixels.isDirect()) throw new GdxRuntimeException("Couldn't setPixels from non-direct ByteBuffer");
ByteBuffer dst = pixmap.getPixels();
BufferUtils.copy(pixels, dst, dst.limit());
}
/** @return the {@link Format} of this Pixmap. */
public Format getFormat () {
return Format.fromGdx2DPixmapFormat(pixmap.getFormat());
}
/** @return the currently set {@link Blending} */
public Blending getBlending () {
return blending;
}
/** @return the currently set {@link Filter} */
public Filter getFilter () {
return filter;
}
/** Response listener for {@link #downloadFromUrl(String, DownloadPixmapResponseListener)} */
public interface DownloadPixmapResponseListener {
/** Called on the render thread when image was downloaded successfully.
* @param pixmap */
void downloadComplete (Pixmap pixmap);
/** Called when image download failed. This might get called on a background thread. */
void downloadFailed (Throwable t);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d/jni/Box2D/Collision/b2CollideEdge.cpp | /*
* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Collision/b2Collision.h>
#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Collision/Shapes/b2EdgeShape.h>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
// Compute contact points for edge versus circle.
// This accounts for edge connectivity.
void b2CollideEdgeAndCircle(b2Manifold* manifold,
const b2EdgeShape* edgeA, const b2Transform& xfA,
const b2CircleShape* circleB, const b2Transform& xfB)
{
manifold->pointCount = 0;
// Compute circle in frame of edge
b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p));
b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2;
b2Vec2 e = B - A;
// Barycentric coordinates
float32 u = b2Dot(e, B - Q);
float32 v = b2Dot(e, Q - A);
float32 radius = edgeA->m_radius + circleB->m_radius;
b2ContactFeature cf;
cf.indexB = 0;
cf.typeB = b2ContactFeature::e_vertex;
// Region A
if (v <= 0.0f)
{
b2Vec2 P = A;
b2Vec2 d = Q - P;
float32 dd = b2Dot(d, d);
if (dd > radius * radius)
{
return;
}
// Is there an edge connected to A?
if (edgeA->m_hasVertex0)
{
b2Vec2 A1 = edgeA->m_vertex0;
b2Vec2 B1 = A;
b2Vec2 e1 = B1 - A1;
float32 u1 = b2Dot(e1, B1 - Q);
// Is the circle in Region AB of the previous edge?
if (u1 > 0.0f)
{
return;
}
}
cf.indexA = 0;
cf.typeA = b2ContactFeature::e_vertex;
manifold->pointCount = 1;
manifold->type = b2Manifold::e_circles;
manifold->localNormal.SetZero();
manifold->localPoint = P;
manifold->points[0].id.key = 0;
manifold->points[0].id.cf = cf;
manifold->points[0].localPoint = circleB->m_p;
return;
}
// Region B
if (u <= 0.0f)
{
b2Vec2 P = B;
b2Vec2 d = Q - P;
float32 dd = b2Dot(d, d);
if (dd > radius * radius)
{
return;
}
// Is there an edge connected to B?
if (edgeA->m_hasVertex3)
{
b2Vec2 B2 = edgeA->m_vertex3;
b2Vec2 A2 = B;
b2Vec2 e2 = B2 - A2;
float32 v2 = b2Dot(e2, Q - A2);
// Is the circle in Region AB of the next edge?
if (v2 > 0.0f)
{
return;
}
}
cf.indexA = 1;
cf.typeA = b2ContactFeature::e_vertex;
manifold->pointCount = 1;
manifold->type = b2Manifold::e_circles;
manifold->localNormal.SetZero();
manifold->localPoint = P;
manifold->points[0].id.key = 0;
manifold->points[0].id.cf = cf;
manifold->points[0].localPoint = circleB->m_p;
return;
}
// Region AB
float32 den = b2Dot(e, e);
b2Assert(den > 0.0f);
b2Vec2 P = (1.0f / den) * (u * A + v * B);
b2Vec2 d = Q - P;
float32 dd = b2Dot(d, d);
if (dd > radius * radius)
{
return;
}
b2Vec2 n(-e.y, e.x);
if (b2Dot(n, Q - A) < 0.0f)
{
n.Set(-n.x, -n.y);
}
n.Normalize();
cf.indexA = 0;
cf.typeA = b2ContactFeature::e_face;
manifold->pointCount = 1;
manifold->type = b2Manifold::e_faceA;
manifold->localNormal = n;
manifold->localPoint = A;
manifold->points[0].id.key = 0;
manifold->points[0].id.cf = cf;
manifold->points[0].localPoint = circleB->m_p;
}
// This structure is used to keep track of the best separating axis.
struct b2EPAxis
{
enum Type
{
e_unknown,
e_edgeA,
e_edgeB
};
Type type;
int32 index;
float32 separation;
};
// This holds polygon B expressed in frame A.
struct b2TempPolygon
{
b2Vec2 vertices[b2_maxPolygonVertices];
b2Vec2 normals[b2_maxPolygonVertices];
int32 count;
};
// Reference face used for clipping
struct b2ReferenceFace
{
int32 i1, i2;
b2Vec2 v1, v2;
b2Vec2 normal;
b2Vec2 sideNormal1;
float32 sideOffset1;
b2Vec2 sideNormal2;
float32 sideOffset2;
};
// This class collides and edge and a polygon, taking into account edge adjacency.
struct b2EPCollider
{
void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA,
const b2PolygonShape* polygonB, const b2Transform& xfB);
b2EPAxis ComputeEdgeSeparation();
b2EPAxis ComputePolygonSeparation();
enum VertexType
{
e_isolated,
e_concave,
e_convex
};
b2TempPolygon m_polygonB;
b2Transform m_xf;
b2Vec2 m_centroidB;
b2Vec2 m_v0, m_v1, m_v2, m_v3;
b2Vec2 m_normal0, m_normal1, m_normal2;
b2Vec2 m_normal;
VertexType m_type1, m_type2;
b2Vec2 m_lowerLimit, m_upperLimit;
float32 m_radius;
bool m_front;
};
// Algorithm:
// 1. Classify v1 and v2
// 2. Classify polygon centroid as front or back
// 3. Flip normal if necessary
// 4. Initialize normal range to [-pi, pi] about face normal
// 5. Adjust normal range according to adjacent edges
// 6. Visit each separating axes, only accept axes within the range
// 7. Return if _any_ axis indicates separation
// 8. Clip
void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA,
const b2PolygonShape* polygonB, const b2Transform& xfB)
{
m_xf = b2MulT(xfA, xfB);
m_centroidB = b2Mul(m_xf, polygonB->m_centroid);
m_v0 = edgeA->m_vertex0;
m_v1 = edgeA->m_vertex1;
m_v2 = edgeA->m_vertex2;
m_v3 = edgeA->m_vertex3;
bool hasVertex0 = edgeA->m_hasVertex0;
bool hasVertex3 = edgeA->m_hasVertex3;
b2Vec2 edge1 = m_v2 - m_v1;
edge1.Normalize();
m_normal1.Set(edge1.y, -edge1.x);
float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1);
float32 offset0 = 0.0f, offset2 = 0.0f;
bool convex1 = false, convex2 = false;
// Is there a preceding edge?
if (hasVertex0)
{
b2Vec2 edge0 = m_v1 - m_v0;
edge0.Normalize();
m_normal0.Set(edge0.y, -edge0.x);
convex1 = b2Cross(edge0, edge1) >= 0.0f;
offset0 = b2Dot(m_normal0, m_centroidB - m_v0);
}
// Is there a following edge?
if (hasVertex3)
{
b2Vec2 edge2 = m_v3 - m_v2;
edge2.Normalize();
m_normal2.Set(edge2.y, -edge2.x);
convex2 = b2Cross(edge1, edge2) > 0.0f;
offset2 = b2Dot(m_normal2, m_centroidB - m_v2);
}
// Determine front or back collision. Determine collision normal limits.
if (hasVertex0 && hasVertex3)
{
if (convex1 && convex2)
{
m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal0;
m_upperLimit = m_normal2;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = -m_normal1;
}
}
else if (convex1)
{
m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f);
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal0;
m_upperLimit = m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal2;
m_upperLimit = -m_normal1;
}
}
else if (convex2)
{
m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f);
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = m_normal2;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = -m_normal0;
}
}
else
{
m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal2;
m_upperLimit = -m_normal0;
}
}
}
else if (hasVertex0)
{
if (convex1)
{
m_front = offset0 >= 0.0f || offset1 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal0;
m_upperLimit = -m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = -m_normal1;
}
}
else
{
m_front = offset0 >= 0.0f && offset1 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = -m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = -m_normal0;
}
}
}
else if (hasVertex3)
{
if (convex2)
{
m_front = offset1 >= 0.0f || offset2 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = m_normal2;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = m_normal1;
}
}
else
{
m_front = offset1 >= 0.0f && offset2 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal2;
m_upperLimit = m_normal1;
}
}
}
else
{
m_front = offset1 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = -m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = m_normal1;
}
}
// Get polygonB in frameA
m_polygonB.count = polygonB->m_count;
for (int32 i = 0; i < polygonB->m_count; ++i)
{
m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]);
m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]);
}
m_radius = 2.0f * b2_polygonRadius;
manifold->pointCount = 0;
b2EPAxis edgeAxis = ComputeEdgeSeparation();
// If no valid normal can be found than this edge should not collide.
if (edgeAxis.type == b2EPAxis::e_unknown)
{
return;
}
if (edgeAxis.separation > m_radius)
{
return;
}
b2EPAxis polygonAxis = ComputePolygonSeparation();
if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius)
{
return;
}
// Use hysteresis for jitter reduction.
const float32 k_relativeTol = 0.98f;
const float32 k_absoluteTol = 0.001f;
b2EPAxis primaryAxis;
if (polygonAxis.type == b2EPAxis::e_unknown)
{
primaryAxis = edgeAxis;
}
else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol)
{
primaryAxis = polygonAxis;
}
else
{
primaryAxis = edgeAxis;
}
b2ClipVertex ie[2];
b2ReferenceFace rf;
if (primaryAxis.type == b2EPAxis::e_edgeA)
{
manifold->type = b2Manifold::e_faceA;
// Search for the polygon normal that is most anti-parallel to the edge normal.
int32 bestIndex = 0;
float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]);
for (int32 i = 1; i < m_polygonB.count; ++i)
{
float32 value = b2Dot(m_normal, m_polygonB.normals[i]);
if (value < bestValue)
{
bestValue = value;
bestIndex = i;
}
}
int32 i1 = bestIndex;
int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0;
ie[0].v = m_polygonB.vertices[i1];
ie[0].id.cf.indexA = 0;
ie[0].id.cf.indexB = static_cast<uint8>(i1);
ie[0].id.cf.typeA = b2ContactFeature::e_face;
ie[0].id.cf.typeB = b2ContactFeature::e_vertex;
ie[1].v = m_polygonB.vertices[i2];
ie[1].id.cf.indexA = 0;
ie[1].id.cf.indexB = static_cast<uint8>(i2);
ie[1].id.cf.typeA = b2ContactFeature::e_face;
ie[1].id.cf.typeB = b2ContactFeature::e_vertex;
if (m_front)
{
rf.i1 = 0;
rf.i2 = 1;
rf.v1 = m_v1;
rf.v2 = m_v2;
rf.normal = m_normal1;
}
else
{
rf.i1 = 1;
rf.i2 = 0;
rf.v1 = m_v2;
rf.v2 = m_v1;
rf.normal = -m_normal1;
}
}
else
{
manifold->type = b2Manifold::e_faceB;
ie[0].v = m_v1;
ie[0].id.cf.indexA = 0;
ie[0].id.cf.indexB = static_cast<uint8>(primaryAxis.index);
ie[0].id.cf.typeA = b2ContactFeature::e_vertex;
ie[0].id.cf.typeB = b2ContactFeature::e_face;
ie[1].v = m_v2;
ie[1].id.cf.indexA = 0;
ie[1].id.cf.indexB = static_cast<uint8>(primaryAxis.index);
ie[1].id.cf.typeA = b2ContactFeature::e_vertex;
ie[1].id.cf.typeB = b2ContactFeature::e_face;
rf.i1 = primaryAxis.index;
rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0;
rf.v1 = m_polygonB.vertices[rf.i1];
rf.v2 = m_polygonB.vertices[rf.i2];
rf.normal = m_polygonB.normals[rf.i1];
}
rf.sideNormal1.Set(rf.normal.y, -rf.normal.x);
rf.sideNormal2 = -rf.sideNormal1;
rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1);
rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2);
// Clip incident edge against extruded edge1 side edges.
b2ClipVertex clipPoints1[2];
b2ClipVertex clipPoints2[2];
int32 np;
// Clip to box side 1
np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1);
if (np < b2_maxManifoldPoints)
{
return;
}
// Clip to negative box side 1
np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2);
if (np < b2_maxManifoldPoints)
{
return;
}
// Now clipPoints2 contains the clipped points.
if (primaryAxis.type == b2EPAxis::e_edgeA)
{
manifold->localNormal = rf.normal;
manifold->localPoint = rf.v1;
}
else
{
manifold->localNormal = polygonB->m_normals[rf.i1];
manifold->localPoint = polygonB->m_vertices[rf.i1];
}
int32 pointCount = 0;
for (int32 i = 0; i < b2_maxManifoldPoints; ++i)
{
float32 separation;
separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1);
if (separation <= m_radius)
{
b2ManifoldPoint* cp = manifold->points + pointCount;
if (primaryAxis.type == b2EPAxis::e_edgeA)
{
cp->localPoint = b2MulT(m_xf, clipPoints2[i].v);
cp->id = clipPoints2[i].id;
}
else
{
cp->localPoint = clipPoints2[i].v;
cp->id.cf.typeA = clipPoints2[i].id.cf.typeB;
cp->id.cf.typeB = clipPoints2[i].id.cf.typeA;
cp->id.cf.indexA = clipPoints2[i].id.cf.indexB;
cp->id.cf.indexB = clipPoints2[i].id.cf.indexA;
}
++pointCount;
}
}
manifold->pointCount = pointCount;
}
b2EPAxis b2EPCollider::ComputeEdgeSeparation()
{
b2EPAxis axis;
axis.type = b2EPAxis::e_edgeA;
axis.index = m_front ? 0 : 1;
axis.separation = FLT_MAX;
for (int32 i = 0; i < m_polygonB.count; ++i)
{
float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1);
if (s < axis.separation)
{
axis.separation = s;
}
}
return axis;
}
b2EPAxis b2EPCollider::ComputePolygonSeparation()
{
b2EPAxis axis;
axis.type = b2EPAxis::e_unknown;
axis.index = -1;
axis.separation = -FLT_MAX;
b2Vec2 perp(-m_normal.y, m_normal.x);
for (int32 i = 0; i < m_polygonB.count; ++i)
{
b2Vec2 n = -m_polygonB.normals[i];
float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1);
float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2);
float32 s = b2Min(s1, s2);
if (s > m_radius)
{
// No collision
axis.type = b2EPAxis::e_edgeB;
axis.index = i;
axis.separation = s;
return axis;
}
// Adjacency
if (b2Dot(n, perp) >= 0.0f)
{
if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop)
{
continue;
}
}
else
{
if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop)
{
continue;
}
}
if (s > axis.separation)
{
axis.type = b2EPAxis::e_edgeB;
axis.index = i;
axis.separation = s;
}
}
return axis;
}
void b2CollideEdgeAndPolygon( b2Manifold* manifold,
const b2EdgeShape* edgeA, const b2Transform& xfA,
const b2PolygonShape* polygonB, const b2Transform& xfB)
{
b2EPCollider collider;
collider.Collide(manifold, edgeA, xfA, polygonB, xfB);
}
| /*
* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Collision/b2Collision.h>
#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Collision/Shapes/b2EdgeShape.h>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
// Compute contact points for edge versus circle.
// This accounts for edge connectivity.
void b2CollideEdgeAndCircle(b2Manifold* manifold,
const b2EdgeShape* edgeA, const b2Transform& xfA,
const b2CircleShape* circleB, const b2Transform& xfB)
{
manifold->pointCount = 0;
// Compute circle in frame of edge
b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p));
b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2;
b2Vec2 e = B - A;
// Barycentric coordinates
float32 u = b2Dot(e, B - Q);
float32 v = b2Dot(e, Q - A);
float32 radius = edgeA->m_radius + circleB->m_radius;
b2ContactFeature cf;
cf.indexB = 0;
cf.typeB = b2ContactFeature::e_vertex;
// Region A
if (v <= 0.0f)
{
b2Vec2 P = A;
b2Vec2 d = Q - P;
float32 dd = b2Dot(d, d);
if (dd > radius * radius)
{
return;
}
// Is there an edge connected to A?
if (edgeA->m_hasVertex0)
{
b2Vec2 A1 = edgeA->m_vertex0;
b2Vec2 B1 = A;
b2Vec2 e1 = B1 - A1;
float32 u1 = b2Dot(e1, B1 - Q);
// Is the circle in Region AB of the previous edge?
if (u1 > 0.0f)
{
return;
}
}
cf.indexA = 0;
cf.typeA = b2ContactFeature::e_vertex;
manifold->pointCount = 1;
manifold->type = b2Manifold::e_circles;
manifold->localNormal.SetZero();
manifold->localPoint = P;
manifold->points[0].id.key = 0;
manifold->points[0].id.cf = cf;
manifold->points[0].localPoint = circleB->m_p;
return;
}
// Region B
if (u <= 0.0f)
{
b2Vec2 P = B;
b2Vec2 d = Q - P;
float32 dd = b2Dot(d, d);
if (dd > radius * radius)
{
return;
}
// Is there an edge connected to B?
if (edgeA->m_hasVertex3)
{
b2Vec2 B2 = edgeA->m_vertex3;
b2Vec2 A2 = B;
b2Vec2 e2 = B2 - A2;
float32 v2 = b2Dot(e2, Q - A2);
// Is the circle in Region AB of the next edge?
if (v2 > 0.0f)
{
return;
}
}
cf.indexA = 1;
cf.typeA = b2ContactFeature::e_vertex;
manifold->pointCount = 1;
manifold->type = b2Manifold::e_circles;
manifold->localNormal.SetZero();
manifold->localPoint = P;
manifold->points[0].id.key = 0;
manifold->points[0].id.cf = cf;
manifold->points[0].localPoint = circleB->m_p;
return;
}
// Region AB
float32 den = b2Dot(e, e);
b2Assert(den > 0.0f);
b2Vec2 P = (1.0f / den) * (u * A + v * B);
b2Vec2 d = Q - P;
float32 dd = b2Dot(d, d);
if (dd > radius * radius)
{
return;
}
b2Vec2 n(-e.y, e.x);
if (b2Dot(n, Q - A) < 0.0f)
{
n.Set(-n.x, -n.y);
}
n.Normalize();
cf.indexA = 0;
cf.typeA = b2ContactFeature::e_face;
manifold->pointCount = 1;
manifold->type = b2Manifold::e_faceA;
manifold->localNormal = n;
manifold->localPoint = A;
manifold->points[0].id.key = 0;
manifold->points[0].id.cf = cf;
manifold->points[0].localPoint = circleB->m_p;
}
// This structure is used to keep track of the best separating axis.
struct b2EPAxis
{
enum Type
{
e_unknown,
e_edgeA,
e_edgeB
};
Type type;
int32 index;
float32 separation;
};
// This holds polygon B expressed in frame A.
struct b2TempPolygon
{
b2Vec2 vertices[b2_maxPolygonVertices];
b2Vec2 normals[b2_maxPolygonVertices];
int32 count;
};
// Reference face used for clipping
struct b2ReferenceFace
{
int32 i1, i2;
b2Vec2 v1, v2;
b2Vec2 normal;
b2Vec2 sideNormal1;
float32 sideOffset1;
b2Vec2 sideNormal2;
float32 sideOffset2;
};
// This class collides and edge and a polygon, taking into account edge adjacency.
struct b2EPCollider
{
void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA,
const b2PolygonShape* polygonB, const b2Transform& xfB);
b2EPAxis ComputeEdgeSeparation();
b2EPAxis ComputePolygonSeparation();
enum VertexType
{
e_isolated,
e_concave,
e_convex
};
b2TempPolygon m_polygonB;
b2Transform m_xf;
b2Vec2 m_centroidB;
b2Vec2 m_v0, m_v1, m_v2, m_v3;
b2Vec2 m_normal0, m_normal1, m_normal2;
b2Vec2 m_normal;
VertexType m_type1, m_type2;
b2Vec2 m_lowerLimit, m_upperLimit;
float32 m_radius;
bool m_front;
};
// Algorithm:
// 1. Classify v1 and v2
// 2. Classify polygon centroid as front or back
// 3. Flip normal if necessary
// 4. Initialize normal range to [-pi, pi] about face normal
// 5. Adjust normal range according to adjacent edges
// 6. Visit each separating axes, only accept axes within the range
// 7. Return if _any_ axis indicates separation
// 8. Clip
void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA,
const b2PolygonShape* polygonB, const b2Transform& xfB)
{
m_xf = b2MulT(xfA, xfB);
m_centroidB = b2Mul(m_xf, polygonB->m_centroid);
m_v0 = edgeA->m_vertex0;
m_v1 = edgeA->m_vertex1;
m_v2 = edgeA->m_vertex2;
m_v3 = edgeA->m_vertex3;
bool hasVertex0 = edgeA->m_hasVertex0;
bool hasVertex3 = edgeA->m_hasVertex3;
b2Vec2 edge1 = m_v2 - m_v1;
edge1.Normalize();
m_normal1.Set(edge1.y, -edge1.x);
float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1);
float32 offset0 = 0.0f, offset2 = 0.0f;
bool convex1 = false, convex2 = false;
// Is there a preceding edge?
if (hasVertex0)
{
b2Vec2 edge0 = m_v1 - m_v0;
edge0.Normalize();
m_normal0.Set(edge0.y, -edge0.x);
convex1 = b2Cross(edge0, edge1) >= 0.0f;
offset0 = b2Dot(m_normal0, m_centroidB - m_v0);
}
// Is there a following edge?
if (hasVertex3)
{
b2Vec2 edge2 = m_v3 - m_v2;
edge2.Normalize();
m_normal2.Set(edge2.y, -edge2.x);
convex2 = b2Cross(edge1, edge2) > 0.0f;
offset2 = b2Dot(m_normal2, m_centroidB - m_v2);
}
// Determine front or back collision. Determine collision normal limits.
if (hasVertex0 && hasVertex3)
{
if (convex1 && convex2)
{
m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal0;
m_upperLimit = m_normal2;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = -m_normal1;
}
}
else if (convex1)
{
m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f);
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal0;
m_upperLimit = m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal2;
m_upperLimit = -m_normal1;
}
}
else if (convex2)
{
m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f);
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = m_normal2;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = -m_normal0;
}
}
else
{
m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal2;
m_upperLimit = -m_normal0;
}
}
}
else if (hasVertex0)
{
if (convex1)
{
m_front = offset0 >= 0.0f || offset1 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal0;
m_upperLimit = -m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = -m_normal1;
}
}
else
{
m_front = offset0 >= 0.0f && offset1 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = -m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = -m_normal0;
}
}
}
else if (hasVertex3)
{
if (convex2)
{
m_front = offset1 >= 0.0f || offset2 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = m_normal2;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = m_normal1;
}
}
else
{
m_front = offset1 >= 0.0f && offset2 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = -m_normal2;
m_upperLimit = m_normal1;
}
}
}
else
{
m_front = offset1 >= 0.0f;
if (m_front)
{
m_normal = m_normal1;
m_lowerLimit = -m_normal1;
m_upperLimit = -m_normal1;
}
else
{
m_normal = -m_normal1;
m_lowerLimit = m_normal1;
m_upperLimit = m_normal1;
}
}
// Get polygonB in frameA
m_polygonB.count = polygonB->m_count;
for (int32 i = 0; i < polygonB->m_count; ++i)
{
m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]);
m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]);
}
m_radius = 2.0f * b2_polygonRadius;
manifold->pointCount = 0;
b2EPAxis edgeAxis = ComputeEdgeSeparation();
// If no valid normal can be found than this edge should not collide.
if (edgeAxis.type == b2EPAxis::e_unknown)
{
return;
}
if (edgeAxis.separation > m_radius)
{
return;
}
b2EPAxis polygonAxis = ComputePolygonSeparation();
if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius)
{
return;
}
// Use hysteresis for jitter reduction.
const float32 k_relativeTol = 0.98f;
const float32 k_absoluteTol = 0.001f;
b2EPAxis primaryAxis;
if (polygonAxis.type == b2EPAxis::e_unknown)
{
primaryAxis = edgeAxis;
}
else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol)
{
primaryAxis = polygonAxis;
}
else
{
primaryAxis = edgeAxis;
}
b2ClipVertex ie[2];
b2ReferenceFace rf;
if (primaryAxis.type == b2EPAxis::e_edgeA)
{
manifold->type = b2Manifold::e_faceA;
// Search for the polygon normal that is most anti-parallel to the edge normal.
int32 bestIndex = 0;
float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]);
for (int32 i = 1; i < m_polygonB.count; ++i)
{
float32 value = b2Dot(m_normal, m_polygonB.normals[i]);
if (value < bestValue)
{
bestValue = value;
bestIndex = i;
}
}
int32 i1 = bestIndex;
int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0;
ie[0].v = m_polygonB.vertices[i1];
ie[0].id.cf.indexA = 0;
ie[0].id.cf.indexB = static_cast<uint8>(i1);
ie[0].id.cf.typeA = b2ContactFeature::e_face;
ie[0].id.cf.typeB = b2ContactFeature::e_vertex;
ie[1].v = m_polygonB.vertices[i2];
ie[1].id.cf.indexA = 0;
ie[1].id.cf.indexB = static_cast<uint8>(i2);
ie[1].id.cf.typeA = b2ContactFeature::e_face;
ie[1].id.cf.typeB = b2ContactFeature::e_vertex;
if (m_front)
{
rf.i1 = 0;
rf.i2 = 1;
rf.v1 = m_v1;
rf.v2 = m_v2;
rf.normal = m_normal1;
}
else
{
rf.i1 = 1;
rf.i2 = 0;
rf.v1 = m_v2;
rf.v2 = m_v1;
rf.normal = -m_normal1;
}
}
else
{
manifold->type = b2Manifold::e_faceB;
ie[0].v = m_v1;
ie[0].id.cf.indexA = 0;
ie[0].id.cf.indexB = static_cast<uint8>(primaryAxis.index);
ie[0].id.cf.typeA = b2ContactFeature::e_vertex;
ie[0].id.cf.typeB = b2ContactFeature::e_face;
ie[1].v = m_v2;
ie[1].id.cf.indexA = 0;
ie[1].id.cf.indexB = static_cast<uint8>(primaryAxis.index);
ie[1].id.cf.typeA = b2ContactFeature::e_vertex;
ie[1].id.cf.typeB = b2ContactFeature::e_face;
rf.i1 = primaryAxis.index;
rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0;
rf.v1 = m_polygonB.vertices[rf.i1];
rf.v2 = m_polygonB.vertices[rf.i2];
rf.normal = m_polygonB.normals[rf.i1];
}
rf.sideNormal1.Set(rf.normal.y, -rf.normal.x);
rf.sideNormal2 = -rf.sideNormal1;
rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1);
rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2);
// Clip incident edge against extruded edge1 side edges.
b2ClipVertex clipPoints1[2];
b2ClipVertex clipPoints2[2];
int32 np;
// Clip to box side 1
np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1);
if (np < b2_maxManifoldPoints)
{
return;
}
// Clip to negative box side 1
np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2);
if (np < b2_maxManifoldPoints)
{
return;
}
// Now clipPoints2 contains the clipped points.
if (primaryAxis.type == b2EPAxis::e_edgeA)
{
manifold->localNormal = rf.normal;
manifold->localPoint = rf.v1;
}
else
{
manifold->localNormal = polygonB->m_normals[rf.i1];
manifold->localPoint = polygonB->m_vertices[rf.i1];
}
int32 pointCount = 0;
for (int32 i = 0; i < b2_maxManifoldPoints; ++i)
{
float32 separation;
separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1);
if (separation <= m_radius)
{
b2ManifoldPoint* cp = manifold->points + pointCount;
if (primaryAxis.type == b2EPAxis::e_edgeA)
{
cp->localPoint = b2MulT(m_xf, clipPoints2[i].v);
cp->id = clipPoints2[i].id;
}
else
{
cp->localPoint = clipPoints2[i].v;
cp->id.cf.typeA = clipPoints2[i].id.cf.typeB;
cp->id.cf.typeB = clipPoints2[i].id.cf.typeA;
cp->id.cf.indexA = clipPoints2[i].id.cf.indexB;
cp->id.cf.indexB = clipPoints2[i].id.cf.indexA;
}
++pointCount;
}
}
manifold->pointCount = pointCount;
}
b2EPAxis b2EPCollider::ComputeEdgeSeparation()
{
b2EPAxis axis;
axis.type = b2EPAxis::e_edgeA;
axis.index = m_front ? 0 : 1;
axis.separation = FLT_MAX;
for (int32 i = 0; i < m_polygonB.count; ++i)
{
float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1);
if (s < axis.separation)
{
axis.separation = s;
}
}
return axis;
}
b2EPAxis b2EPCollider::ComputePolygonSeparation()
{
b2EPAxis axis;
axis.type = b2EPAxis::e_unknown;
axis.index = -1;
axis.separation = -FLT_MAX;
b2Vec2 perp(-m_normal.y, m_normal.x);
for (int32 i = 0; i < m_polygonB.count; ++i)
{
b2Vec2 n = -m_polygonB.normals[i];
float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1);
float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2);
float32 s = b2Min(s1, s2);
if (s > m_radius)
{
// No collision
axis.type = b2EPAxis::e_edgeB;
axis.index = i;
axis.separation = s;
return axis;
}
// Adjacency
if (b2Dot(n, perp) >= 0.0f)
{
if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop)
{
continue;
}
}
else
{
if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop)
{
continue;
}
}
if (s > axis.separation)
{
axis.type = b2EPAxis::e_edgeB;
axis.index = i;
axis.separation = s;
}
}
return axis;
}
void b2CollideEdgeAndPolygon( b2Manifold* manifold,
const b2EdgeShape* edgeA, const b2Transform& xfA,
const b2PolygonShape* polygonB, const b2Transform& xfB)
{
b2EPCollider collider;
collider.Collide(manifold, edgeA, xfA, polygonB, xfB);
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/Vector2dTest.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.ScreenUtils;
public class Vector2dTest extends GdxTest {
private static final float DURATION = 2.0f;
private ShapeRenderer renderer;
private OrthographicCamera camera;
private Vector2 rotating = new Vector2(Vector2.X);
private Vector2 scalingX = new Vector2(Vector2.Y);
private Vector2 scalingY = new Vector2(Vector2.X);
private Vector2 lerping1 = new Vector2(Vector2.X);
private Vector2 lerpTarget = new Vector2(Vector2.Y);
private Vector2 sum = new Vector2().add(Vector2.X).add(Vector2.Y).nor();
private Vector2 mash = new Vector2(Vector2.Y);
private Interpolation interpolator = Interpolation.swing;
private Vector2 lerping2 = new Vector2(Vector2.X);
private Vector2 lerpStart2 = new Vector2(Vector2.X);
private Vector2 lerpTarget2 = new Vector2(Vector2.Y);
private float timePassed = 0;
private final long start = System.currentTimeMillis();
@Override
public void create () {
renderer = new ShapeRenderer();
}
private void renderVectorAt (float x, float y, Vector2 v) {
renderer.line(x, y, x + v.x, y + v.y);
}
@Override
public void render () {
ScreenUtils.clear(0, 0, 0, 0);
renderer.setProjectionMatrix(camera.combined);
// Render the 'lerp' vector target as a circle
renderer.begin(ShapeType.Filled);
renderer.setColor(1.0f, 0, 0, 0.3f);
renderer.circle(-2 + lerpTarget.x, 2 + lerpTarget.y, 0.08f, 16);
renderer.circle(-4 + lerpTarget2.x, 0 + lerpTarget2.y, 0.08f, 16);
renderer.end();
renderer.begin(ShapeType.Line);
// Render the three fixed X, Y and sum vectors:
renderer.setColor(Color.RED);
renderVectorAt(0, 0, Vector2.X);
renderer.setColor(Color.GREEN);
renderVectorAt(0, 0, Vector2.Y);
renderer.setColor(Color.YELLOW);
renderVectorAt(0, 0, sum);
final float changeRate = Gdx.graphics.getDeltaTime();
renderer.setColor(Color.WHITE);
renderVectorAt(2, 2, rotating);
rotating.rotateDeg(93 * changeRate);
renderVectorAt(2, -2, scalingX);
scalingX.set(0, MathUtils.sin((System.currentTimeMillis() - start) / 520.0f));
renderVectorAt(2, -2, scalingY);
scalingY.set(MathUtils.cos((System.currentTimeMillis() - start) / 260.0f), 0);
renderVectorAt(-2, 2, lerping1);
lerping1.lerp(lerpTarget, 0.025f);
if (lerping1.epsilonEquals(lerpTarget, 0.05f)) {
lerpTarget.set(-1.0f + MathUtils.random(2.0f), -1.0f + MathUtils.random(2.0f)).nor();
}
timePassed += Gdx.graphics.getDeltaTime();
renderVectorAt(-4, 0, lerping2);
lerping2.set(lerpStart2);
lerping2.interpolate(lerpTarget2, MathUtils.clamp(timePassed / DURATION, 0, 1), interpolator);
if (lerping2.epsilonEquals(lerpTarget2, 0.025f)) {
lerpTarget2.set(-1.0f + MathUtils.random(2.0f), -1.0f + MathUtils.random(2.0f)).nor();
lerpStart2.set(lerping2);
timePassed = 0;
}
renderVectorAt(-2, -2, mash);
mash.set(0, 0).add(rotating).add(scalingX).add(scalingY).add(lerping1);
renderer.end();
}
@Override
public void resize (int width, int height) {
float ratio = ((float)Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight());
int h = 10;
int w = (int)(h * ratio);
camera = new OrthographicCamera(w, h);
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.ScreenUtils;
public class Vector2dTest extends GdxTest {
private static final float DURATION = 2.0f;
private ShapeRenderer renderer;
private OrthographicCamera camera;
private Vector2 rotating = new Vector2(Vector2.X);
private Vector2 scalingX = new Vector2(Vector2.Y);
private Vector2 scalingY = new Vector2(Vector2.X);
private Vector2 lerping1 = new Vector2(Vector2.X);
private Vector2 lerpTarget = new Vector2(Vector2.Y);
private Vector2 sum = new Vector2().add(Vector2.X).add(Vector2.Y).nor();
private Vector2 mash = new Vector2(Vector2.Y);
private Interpolation interpolator = Interpolation.swing;
private Vector2 lerping2 = new Vector2(Vector2.X);
private Vector2 lerpStart2 = new Vector2(Vector2.X);
private Vector2 lerpTarget2 = new Vector2(Vector2.Y);
private float timePassed = 0;
private final long start = System.currentTimeMillis();
@Override
public void create () {
renderer = new ShapeRenderer();
}
private void renderVectorAt (float x, float y, Vector2 v) {
renderer.line(x, y, x + v.x, y + v.y);
}
@Override
public void render () {
ScreenUtils.clear(0, 0, 0, 0);
renderer.setProjectionMatrix(camera.combined);
// Render the 'lerp' vector target as a circle
renderer.begin(ShapeType.Filled);
renderer.setColor(1.0f, 0, 0, 0.3f);
renderer.circle(-2 + lerpTarget.x, 2 + lerpTarget.y, 0.08f, 16);
renderer.circle(-4 + lerpTarget2.x, 0 + lerpTarget2.y, 0.08f, 16);
renderer.end();
renderer.begin(ShapeType.Line);
// Render the three fixed X, Y and sum vectors:
renderer.setColor(Color.RED);
renderVectorAt(0, 0, Vector2.X);
renderer.setColor(Color.GREEN);
renderVectorAt(0, 0, Vector2.Y);
renderer.setColor(Color.YELLOW);
renderVectorAt(0, 0, sum);
final float changeRate = Gdx.graphics.getDeltaTime();
renderer.setColor(Color.WHITE);
renderVectorAt(2, 2, rotating);
rotating.rotateDeg(93 * changeRate);
renderVectorAt(2, -2, scalingX);
scalingX.set(0, MathUtils.sin((System.currentTimeMillis() - start) / 520.0f));
renderVectorAt(2, -2, scalingY);
scalingY.set(MathUtils.cos((System.currentTimeMillis() - start) / 260.0f), 0);
renderVectorAt(-2, 2, lerping1);
lerping1.lerp(lerpTarget, 0.025f);
if (lerping1.epsilonEquals(lerpTarget, 0.05f)) {
lerpTarget.set(-1.0f + MathUtils.random(2.0f), -1.0f + MathUtils.random(2.0f)).nor();
}
timePassed += Gdx.graphics.getDeltaTime();
renderVectorAt(-4, 0, lerping2);
lerping2.set(lerpStart2);
lerping2.interpolate(lerpTarget2, MathUtils.clamp(timePassed / DURATION, 0, 1), interpolator);
if (lerping2.epsilonEquals(lerpTarget2, 0.025f)) {
lerpTarget2.set(-1.0f + MathUtils.random(2.0f), -1.0f + MathUtils.random(2.0f)).nor();
lerpStart2.set(lerping2);
timePassed = 0;
}
renderVectorAt(-2, -2, mash);
mash.set(0, 0).add(rotating).add(scalingX).add(scalingY).add(lerping1);
renderer.end();
}
@Override
public void resize (int width, int height) {
float ratio = ((float)Gdx.graphics.getWidth() / (float)Gdx.graphics.getHeight());
int h = 10;
int w = (int)(h * ratio);
camera = new OrthographicCamera(w, h);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests-android/res/xml/daydream.xml | <dream xmlns:android="http://schemas.android.com/apk/res/android"
android:settingsActivity="com.badlogic.gdx.tests.android/.DaydreamSettings" /> | <dream xmlns:android="http://schemas.android.com/apk/res/android"
android:settingsActivity="com.badlogic.gdx.tests.android/.DaydreamSettings" /> | -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d/src/com/badlogic/gdx/physics/box2d/joints/DistanceJointDef.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.physics.box2d.joints;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.JointDef;
/** Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance
* joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This
* helps when saving and loading a game.
* @warning Do not use a zero or short length. */
public class DistanceJointDef extends JointDef {
public DistanceJointDef () {
type = JointType.DistanceJoint;
}
/** Initialize the bodies, anchors, and length using the world anchors. */
public void initialize (Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB) {
this.bodyA = bodyA;
this.bodyB = bodyB;
this.localAnchorA.set(bodyA.getLocalPoint(anchorA));
this.localAnchorB.set(bodyB.getLocalPoint(anchorB));
this.length = anchorA.dst(anchorB);
}
/** The local anchor point relative to body1's origin. */
public final Vector2 localAnchorA = new Vector2();
/** The local anchor point relative to body2's origin. */
public final Vector2 localAnchorB = new Vector2();
/** The natural length between the anchor points. */
public float length = 1;
/** The mass-spring-damper frequency in Hertz. */
public float frequencyHz = 0;
/** The damping ratio. 0 = no damping, 1 = critical damping. */
public float dampingRatio = 0;
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.physics.box2d.joints;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.JointDef;
/** Distance joint definition. This requires defining an anchor point on both bodies and the non-zero length of the distance
* joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This
* helps when saving and loading a game.
* @warning Do not use a zero or short length. */
public class DistanceJointDef extends JointDef {
public DistanceJointDef () {
type = JointType.DistanceJoint;
}
/** Initialize the bodies, anchors, and length using the world anchors. */
public void initialize (Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB) {
this.bodyA = bodyA;
this.bodyB = bodyB;
this.localAnchorA.set(bodyA.getLocalPoint(anchorA));
this.localAnchorB.set(bodyB.getLocalPoint(anchorB));
this.length = anchorA.dst(anchorB);
}
/** The local anchor point relative to body1's origin. */
public final Vector2 localAnchorA = new Vector2();
/** The local anchor point relative to body2's origin. */
public final Vector2 localAnchorB = new Vector2();
/** The natural length between the anchor points. */
public float length = 1;
/** The mass-spring-damper frequency in Hertz. */
public float frequencyHz = 0;
/** The damping ratio. 0 = no damping, 1 = critical damping. */
public float dampingRatio = 0;
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-box2d/gdx-box2d/jni/Box2D/Dynamics/Joints/b2MotorJoint.cpp | /*
* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2MotorJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB)
{
bodyA = bA;
bodyB = bB;
b2Vec2 xB = bodyB->GetPosition();
linearOffset = bodyA->GetLocalPoint(xB);
float32 angleA = bodyA->GetAngle();
float32 angleB = bodyB->GetAngle();
angularOffset = angleB - angleA;
}
b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def)
: b2Joint(def)
{
m_linearOffset = def->linearOffset;
m_angularOffset = def->angularOffset;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
m_correctionFactor = def->correctionFactor;
}
void b2MotorJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, -m_localCenterA);
m_rB = b2Mul(qB, -m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0f)
{
m_angularMass = 1.0f / m_angularMass;
}
m_linearError = cB + m_rB - cA - m_rA - b2Mul(qA, m_linearOffset);
m_angularError = aB - aA - m_angularOffset;
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2MotorJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
float32 h = data.step.dt;
float32 inv_h = data.step.inv_dt;
// Solve angular friction
{
float32 Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError;
float32 impulse = -m_angularMass * Cdot;
float32 oldImpulse = m_angularImpulse;
float32 maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor * m_linearError;
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float32 maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2MotorJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2MotorJoint::GetAnchorA() const
{
return m_bodyA->GetPosition();
}
b2Vec2 b2MotorJoint::GetAnchorB() const
{
return m_bodyB->GetPosition();
}
b2Vec2 b2MotorJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2MotorJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2MotorJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float32 b2MotorJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2MotorJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float32 b2MotorJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2MotorJoint::SetCorrectionFactor(float32 factor)
{
b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f);
m_correctionFactor = factor;
}
float32 b2MotorJoint::GetCorrectionFactor() const
{
return m_correctionFactor;
}
void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset)
{
if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_linearOffset = linearOffset;
}
}
const b2Vec2& b2MotorJoint::GetLinearOffset() const
{
return m_linearOffset;
}
void b2MotorJoint::SetAngularOffset(float32 angularOffset)
{
if (angularOffset != m_angularOffset)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_angularOffset = angularOffset;
}
}
float32 b2MotorJoint::GetAngularOffset() const
{
return m_angularOffset;
}
void b2MotorJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2MotorJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.linearOffset.Set(%.15lef, %.15lef);\n", m_linearOffset.x, m_linearOffset.y);
b2Log(" jd.angularOffset = %.15lef;\n", m_angularOffset);
b2Log(" jd.maxForce = %.15lef;\n", m_maxForce);
b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque);
b2Log(" jd.correctionFactor = %.15lef;\n", m_correctionFactor);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| /*
* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <Box2D/Dynamics/Joints/b2MotorJoint.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2TimeStep.h>
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
void b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB)
{
bodyA = bA;
bodyB = bB;
b2Vec2 xB = bodyB->GetPosition();
linearOffset = bodyA->GetLocalPoint(xB);
float32 angleA = bodyA->GetAngle();
float32 angleB = bodyB->GetAngle();
angularOffset = angleB - angleA;
}
b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def)
: b2Joint(def)
{
m_linearOffset = def->linearOffset;
m_angularOffset = def->angularOffset;
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
m_maxForce = def->maxForce;
m_maxTorque = def->maxTorque;
m_correctionFactor = def->correctionFactor;
}
void b2MotorJoint::InitVelocityConstraints(const b2SolverData& data)
{
m_indexA = m_bodyA->m_islandIndex;
m_indexB = m_bodyB->m_islandIndex;
m_localCenterA = m_bodyA->m_sweep.localCenter;
m_localCenterB = m_bodyB->m_sweep.localCenter;
m_invMassA = m_bodyA->m_invMass;
m_invMassB = m_bodyB->m_invMass;
m_invIA = m_bodyA->m_invI;
m_invIB = m_bodyB->m_invI;
b2Vec2 cA = data.positions[m_indexA].c;
float32 aA = data.positions[m_indexA].a;
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 cB = data.positions[m_indexB].c;
float32 aB = data.positions[m_indexB].a;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
b2Rot qA(aA), qB(aB);
// Compute the effective mass matrix.
m_rA = b2Mul(qA, -m_localCenterA);
m_rB = b2Mul(qB, -m_localCenterB);
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
b2Mat22 K;
K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y;
K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x;
m_linearMass = K.GetInverse();
m_angularMass = iA + iB;
if (m_angularMass > 0.0f)
{
m_angularMass = 1.0f / m_angularMass;
}
m_linearError = cB + m_rB - cA - m_rA - b2Mul(qA, m_linearOffset);
m_angularError = aB - aA - m_angularOffset;
if (data.step.warmStarting)
{
// Scale impulses to support a variable time step.
m_linearImpulse *= data.step.dtRatio;
m_angularImpulse *= data.step.dtRatio;
b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y);
vA -= mA * P;
wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse);
vB += mB * P;
wB += iB * (b2Cross(m_rB, P) + m_angularImpulse);
}
else
{
m_linearImpulse.SetZero();
m_angularImpulse = 0.0f;
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
void b2MotorJoint::SolveVelocityConstraints(const b2SolverData& data)
{
b2Vec2 vA = data.velocities[m_indexA].v;
float32 wA = data.velocities[m_indexA].w;
b2Vec2 vB = data.velocities[m_indexB].v;
float32 wB = data.velocities[m_indexB].w;
float32 mA = m_invMassA, mB = m_invMassB;
float32 iA = m_invIA, iB = m_invIB;
float32 h = data.step.dt;
float32 inv_h = data.step.inv_dt;
// Solve angular friction
{
float32 Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError;
float32 impulse = -m_angularMass * Cdot;
float32 oldImpulse = m_angularImpulse;
float32 maxImpulse = h * m_maxTorque;
m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve linear friction
{
b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor * m_linearError;
b2Vec2 impulse = -b2Mul(m_linearMass, Cdot);
b2Vec2 oldImpulse = m_linearImpulse;
m_linearImpulse += impulse;
float32 maxImpulse = h * m_maxForce;
if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse)
{
m_linearImpulse.Normalize();
m_linearImpulse *= maxImpulse;
}
impulse = m_linearImpulse - oldImpulse;
vA -= mA * impulse;
wA -= iA * b2Cross(m_rA, impulse);
vB += mB * impulse;
wB += iB * b2Cross(m_rB, impulse);
}
data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
bool b2MotorJoint::SolvePositionConstraints(const b2SolverData& data)
{
B2_NOT_USED(data);
return true;
}
b2Vec2 b2MotorJoint::GetAnchorA() const
{
return m_bodyA->GetPosition();
}
b2Vec2 b2MotorJoint::GetAnchorB() const
{
return m_bodyB->GetPosition();
}
b2Vec2 b2MotorJoint::GetReactionForce(float32 inv_dt) const
{
return inv_dt * m_linearImpulse;
}
float32 b2MotorJoint::GetReactionTorque(float32 inv_dt) const
{
return inv_dt * m_angularImpulse;
}
void b2MotorJoint::SetMaxForce(float32 force)
{
b2Assert(b2IsValid(force) && force >= 0.0f);
m_maxForce = force;
}
float32 b2MotorJoint::GetMaxForce() const
{
return m_maxForce;
}
void b2MotorJoint::SetMaxTorque(float32 torque)
{
b2Assert(b2IsValid(torque) && torque >= 0.0f);
m_maxTorque = torque;
}
float32 b2MotorJoint::GetMaxTorque() const
{
return m_maxTorque;
}
void b2MotorJoint::SetCorrectionFactor(float32 factor)
{
b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f);
m_correctionFactor = factor;
}
float32 b2MotorJoint::GetCorrectionFactor() const
{
return m_correctionFactor;
}
void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset)
{
if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_linearOffset = linearOffset;
}
}
const b2Vec2& b2MotorJoint::GetLinearOffset() const
{
return m_linearOffset;
}
void b2MotorJoint::SetAngularOffset(float32 angularOffset)
{
if (angularOffset != m_angularOffset)
{
m_bodyA->SetAwake(true);
m_bodyB->SetAwake(true);
m_angularOffset = angularOffset;
}
}
float32 b2MotorJoint::GetAngularOffset() const
{
return m_angularOffset;
}
void b2MotorJoint::Dump()
{
int32 indexA = m_bodyA->m_islandIndex;
int32 indexB = m_bodyB->m_islandIndex;
b2Log(" b2MotorJointDef jd;\n");
b2Log(" jd.bodyA = bodies[%d];\n", indexA);
b2Log(" jd.bodyB = bodies[%d];\n", indexB);
b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected);
b2Log(" jd.linearOffset.Set(%.15lef, %.15lef);\n", m_linearOffset.x, m_linearOffset.y);
b2Log(" jd.angularOffset = %.15lef;\n", m_angularOffset);
b2Log(" jd.maxForce = %.15lef;\n", m_maxForce);
b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque);
b2Log(" jd.correctionFactor = %.15lef;\n", m_correctionFactor);
b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index);
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests-android/assets/data/i18n/message1_en.properties | msg=English test message
| msg=English test message
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/src/bullet/BulletCollision/BroadphaseCollision/btOverlappingPairCache.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_OVERLAPPING_PAIR_CACHE_H
#define BT_OVERLAPPING_PAIR_CACHE_H
#include "btBroadphaseInterface.h"
#include "btBroadphaseProxy.h"
#include "btOverlappingPairCallback.h"
#include "LinearMath/btAlignedObjectArray.h"
class btDispatcher;
typedef btAlignedObjectArray<btBroadphasePair> btBroadphasePairArray;
struct btOverlapCallback
{
virtual ~btOverlapCallback()
{}
//return true for deletion of the pair
virtual bool processOverlap(btBroadphasePair& pair) = 0;
};
struct btOverlapFilterCallback
{
virtual ~btOverlapFilterCallback()
{}
// return true when pairs need collision
virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const = 0;
};
extern int gRemovePairs;
extern int gAddedPairs;
extern int gFindPairs;
const int BT_NULL_PAIR=0xffffffff;
///The btOverlappingPairCache provides an interface for overlapping pair management (add, remove, storage), used by the btBroadphaseInterface broadphases.
///The btHashedOverlappingPairCache and btSortedOverlappingPairCache classes are two implementations.
class btOverlappingPairCache : public btOverlappingPairCallback
{
public:
virtual ~btOverlappingPairCache() {} // this is needed so we can get to the derived class destructor
virtual btBroadphasePair* getOverlappingPairArrayPtr() = 0;
virtual const btBroadphasePair* getOverlappingPairArrayPtr() const = 0;
virtual btBroadphasePairArray& getOverlappingPairArray() = 0;
virtual void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher) = 0;
virtual int getNumOverlappingPairs() const = 0;
virtual void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher) = 0;
virtual void setOverlapFilterCallback(btOverlapFilterCallback* callback) = 0;
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher) = 0;
virtual btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) = 0;
virtual bool hasDeferredRemoval() = 0;
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)=0;
virtual void sortOverlappingPairs(btDispatcher* dispatcher) = 0;
};
/// Hash-space based Pair Cache, thanks to Erin Catto, Box2D, http://www.box2d.org, and Pierre Terdiman, Codercorner, http://codercorner.com
ATTRIBUTE_ALIGNED16(class) btHashedOverlappingPairCache : public btOverlappingPairCache
{
btBroadphasePairArray m_overlappingPairArray;
btOverlapFilterCallback* m_overlapFilterCallback;
protected:
btAlignedObjectArray<int> m_hashTable;
btAlignedObjectArray<int> m_next;
btOverlappingPairCallback* m_ghostPairCallback;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btHashedOverlappingPairCache();
virtual ~btHashedOverlappingPairCache();
void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher);
SIMD_FORCE_INLINE bool needsBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const
{
if (m_overlapFilterCallback)
return m_overlapFilterCallback->needBroadphaseCollision(proxy0,proxy1);
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
// Add a pair and return the new pair. If the pair already exists,
// no new pair is created and the old one is returned.
virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1)
{
gAddedPairs++;
if (!needsBroadphaseCollision(proxy0,proxy1))
return 0;
return internalAddPair(proxy0,proxy1);
}
void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher);
virtual btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btBroadphasePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher);
btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1);
int GetCount() const { return m_overlappingPairArray.size(); }
// btBroadphasePair* GetPairs() { return m_pairs; }
btOverlapFilterCallback* getOverlapFilterCallback()
{
return m_overlapFilterCallback;
}
void setOverlapFilterCallback(btOverlapFilterCallback* callback)
{
m_overlapFilterCallback = callback;
}
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
private:
btBroadphasePair* internalAddPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
void growTables();
SIMD_FORCE_INLINE bool equalsPair(const btBroadphasePair& pair, int proxyId1, int proxyId2)
{
return pair.m_pProxy0->getUid() == proxyId1 && pair.m_pProxy1->getUid() == proxyId2;
}
/*
// Thomas Wang's hash, see: http://www.concentric.net/~Ttwang/tech/inthash.htm
// This assumes proxyId1 and proxyId2 are 16-bit.
SIMD_FORCE_INLINE int getHash(int proxyId1, int proxyId2)
{
int key = (proxyId2 << 16) | proxyId1;
key = ~key + (key << 15);
key = key ^ (key >> 12);
key = key + (key << 2);
key = key ^ (key >> 4);
key = key * 2057;
key = key ^ (key >> 16);
return key;
}
*/
SIMD_FORCE_INLINE unsigned int getHash(unsigned int proxyId1, unsigned int proxyId2)
{
unsigned int key = proxyId1 | (proxyId2 << 16);
// Thomas Wang's hash
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
SIMD_FORCE_INLINE btBroadphasePair* internalFindPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1, int hash)
{
int proxyId1 = proxy0->getUid();
int proxyId2 = proxy1->getUid();
#if 0 // wrong, 'equalsPair' use unsorted uids, copy-past devil striked again. Nat.
if (proxyId1 > proxyId2)
btSwap(proxyId1, proxyId2);
#endif
int index = m_hashTable[hash];
while( index != BT_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyId1, proxyId2) == false)
{
index = m_next[index];
}
if ( index == BT_NULL_PAIR )
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
virtual bool hasDeferredRemoval()
{
return false;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)
{
m_ghostPairCallback = ghostPairCallback;
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher);
};
///btSortedOverlappingPairCache maintains the objects with overlapping AABB
///Typically managed by the Broadphase, Axis3Sweep or btSimpleBroadphase
class btSortedOverlappingPairCache : public btOverlappingPairCache
{
protected:
//avoid brute-force finding all the time
btBroadphasePairArray m_overlappingPairArray;
//during the dispatch, check that user doesn't destroy/create proxy
bool m_blockedForChanges;
///by default, do the removal during the pair traversal
bool m_hasDeferredRemoval;
//if set, use the callback instead of the built in filter in needBroadphaseCollision
btOverlapFilterCallback* m_overlapFilterCallback;
btOverlappingPairCallback* m_ghostPairCallback;
public:
btSortedOverlappingPairCache();
virtual ~btSortedOverlappingPairCache();
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher);
void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher);
void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher);
btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
btBroadphasePair* findPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
inline bool needsBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const
{
if (m_overlapFilterCallback)
return m_overlapFilterCallback->needBroadphaseCollision(proxy0,proxy1);
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btBroadphasePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
btOverlapFilterCallback* getOverlapFilterCallback()
{
return m_overlapFilterCallback;
}
void setOverlapFilterCallback(btOverlapFilterCallback* callback)
{
m_overlapFilterCallback = callback;
}
virtual bool hasDeferredRemoval()
{
return m_hasDeferredRemoval;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)
{
m_ghostPairCallback = ghostPairCallback;
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher);
};
///btNullPairCache skips add/removal of overlapping pairs. Userful for benchmarking and unit testing.
class btNullPairCache : public btOverlappingPairCache
{
btBroadphasePairArray m_overlappingPairArray;
public:
virtual btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
virtual void cleanOverlappingPair(btBroadphasePair& /*pair*/,btDispatcher* /*dispatcher*/)
{
}
virtual int getNumOverlappingPairs() const
{
return 0;
}
virtual void cleanProxyFromPairs(btBroadphaseProxy* /*proxy*/,btDispatcher* /*dispatcher*/)
{
}
virtual void setOverlapFilterCallback(btOverlapFilterCallback* /*callback*/)
{
}
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* /*dispatcher*/)
{
}
virtual btBroadphasePair* findPair(btBroadphaseProxy* /*proxy0*/, btBroadphaseProxy* /*proxy1*/)
{
return 0;
}
virtual bool hasDeferredRemoval()
{
return true;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* /* ghostPairCallback */)
{
}
virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* /*proxy0*/,btBroadphaseProxy* /*proxy1*/)
{
return 0;
}
virtual void* removeOverlappingPair(btBroadphaseProxy* /*proxy0*/,btBroadphaseProxy* /*proxy1*/,btDispatcher* /*dispatcher*/)
{
return 0;
}
virtual void removeOverlappingPairsContainingProxy(btBroadphaseProxy* /*proxy0*/,btDispatcher* /*dispatcher*/)
{
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher)
{
(void) dispatcher;
}
};
#endif //BT_OVERLAPPING_PAIR_CACHE_H
| /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef BT_OVERLAPPING_PAIR_CACHE_H
#define BT_OVERLAPPING_PAIR_CACHE_H
#include "btBroadphaseInterface.h"
#include "btBroadphaseProxy.h"
#include "btOverlappingPairCallback.h"
#include "LinearMath/btAlignedObjectArray.h"
class btDispatcher;
typedef btAlignedObjectArray<btBroadphasePair> btBroadphasePairArray;
struct btOverlapCallback
{
virtual ~btOverlapCallback()
{}
//return true for deletion of the pair
virtual bool processOverlap(btBroadphasePair& pair) = 0;
};
struct btOverlapFilterCallback
{
virtual ~btOverlapFilterCallback()
{}
// return true when pairs need collision
virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const = 0;
};
extern int gRemovePairs;
extern int gAddedPairs;
extern int gFindPairs;
const int BT_NULL_PAIR=0xffffffff;
///The btOverlappingPairCache provides an interface for overlapping pair management (add, remove, storage), used by the btBroadphaseInterface broadphases.
///The btHashedOverlappingPairCache and btSortedOverlappingPairCache classes are two implementations.
class btOverlappingPairCache : public btOverlappingPairCallback
{
public:
virtual ~btOverlappingPairCache() {} // this is needed so we can get to the derived class destructor
virtual btBroadphasePair* getOverlappingPairArrayPtr() = 0;
virtual const btBroadphasePair* getOverlappingPairArrayPtr() const = 0;
virtual btBroadphasePairArray& getOverlappingPairArray() = 0;
virtual void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher) = 0;
virtual int getNumOverlappingPairs() const = 0;
virtual void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher) = 0;
virtual void setOverlapFilterCallback(btOverlapFilterCallback* callback) = 0;
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher) = 0;
virtual btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1) = 0;
virtual bool hasDeferredRemoval() = 0;
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)=0;
virtual void sortOverlappingPairs(btDispatcher* dispatcher) = 0;
};
/// Hash-space based Pair Cache, thanks to Erin Catto, Box2D, http://www.box2d.org, and Pierre Terdiman, Codercorner, http://codercorner.com
ATTRIBUTE_ALIGNED16(class) btHashedOverlappingPairCache : public btOverlappingPairCache
{
btBroadphasePairArray m_overlappingPairArray;
btOverlapFilterCallback* m_overlapFilterCallback;
protected:
btAlignedObjectArray<int> m_hashTable;
btAlignedObjectArray<int> m_next;
btOverlappingPairCallback* m_ghostPairCallback;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btHashedOverlappingPairCache();
virtual ~btHashedOverlappingPairCache();
void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher);
SIMD_FORCE_INLINE bool needsBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const
{
if (m_overlapFilterCallback)
return m_overlapFilterCallback->needBroadphaseCollision(proxy0,proxy1);
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
// Add a pair and return the new pair. If the pair already exists,
// no new pair is created and the old one is returned.
virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1)
{
gAddedPairs++;
if (!needsBroadphaseCollision(proxy0,proxy1))
return 0;
return internalAddPair(proxy0,proxy1);
}
void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher);
virtual btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btBroadphasePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher);
btBroadphasePair* findPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1);
int GetCount() const { return m_overlappingPairArray.size(); }
// btBroadphasePair* GetPairs() { return m_pairs; }
btOverlapFilterCallback* getOverlapFilterCallback()
{
return m_overlapFilterCallback;
}
void setOverlapFilterCallback(btOverlapFilterCallback* callback)
{
m_overlapFilterCallback = callback;
}
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
private:
btBroadphasePair* internalAddPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
void growTables();
SIMD_FORCE_INLINE bool equalsPair(const btBroadphasePair& pair, int proxyId1, int proxyId2)
{
return pair.m_pProxy0->getUid() == proxyId1 && pair.m_pProxy1->getUid() == proxyId2;
}
/*
// Thomas Wang's hash, see: http://www.concentric.net/~Ttwang/tech/inthash.htm
// This assumes proxyId1 and proxyId2 are 16-bit.
SIMD_FORCE_INLINE int getHash(int proxyId1, int proxyId2)
{
int key = (proxyId2 << 16) | proxyId1;
key = ~key + (key << 15);
key = key ^ (key >> 12);
key = key + (key << 2);
key = key ^ (key >> 4);
key = key * 2057;
key = key ^ (key >> 16);
return key;
}
*/
SIMD_FORCE_INLINE unsigned int getHash(unsigned int proxyId1, unsigned int proxyId2)
{
unsigned int key = proxyId1 | (proxyId2 << 16);
// Thomas Wang's hash
key += ~(key << 15);
key ^= (key >> 10);
key += (key << 3);
key ^= (key >> 6);
key += ~(key << 11);
key ^= (key >> 16);
return key;
}
SIMD_FORCE_INLINE btBroadphasePair* internalFindPair(btBroadphaseProxy* proxy0, btBroadphaseProxy* proxy1, int hash)
{
int proxyId1 = proxy0->getUid();
int proxyId2 = proxy1->getUid();
#if 0 // wrong, 'equalsPair' use unsorted uids, copy-past devil striked again. Nat.
if (proxyId1 > proxyId2)
btSwap(proxyId1, proxyId2);
#endif
int index = m_hashTable[hash];
while( index != BT_NULL_PAIR && equalsPair(m_overlappingPairArray[index], proxyId1, proxyId2) == false)
{
index = m_next[index];
}
if ( index == BT_NULL_PAIR )
{
return NULL;
}
btAssert(index < m_overlappingPairArray.size());
return &m_overlappingPairArray[index];
}
virtual bool hasDeferredRemoval()
{
return false;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)
{
m_ghostPairCallback = ghostPairCallback;
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher);
};
///btSortedOverlappingPairCache maintains the objects with overlapping AABB
///Typically managed by the Broadphase, Axis3Sweep or btSimpleBroadphase
class btSortedOverlappingPairCache : public btOverlappingPairCache
{
protected:
//avoid brute-force finding all the time
btBroadphasePairArray m_overlappingPairArray;
//during the dispatch, check that user doesn't destroy/create proxy
bool m_blockedForChanges;
///by default, do the removal during the pair traversal
bool m_hasDeferredRemoval;
//if set, use the callback instead of the built in filter in needBroadphaseCollision
btOverlapFilterCallback* m_overlapFilterCallback;
btOverlappingPairCallback* m_ghostPairCallback;
public:
btSortedOverlappingPairCache();
virtual ~btSortedOverlappingPairCache();
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* dispatcher);
void* removeOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1,btDispatcher* dispatcher);
void cleanOverlappingPair(btBroadphasePair& pair,btDispatcher* dispatcher);
btBroadphasePair* addOverlappingPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
btBroadphasePair* findPair(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1);
void cleanProxyFromPairs(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
void removeOverlappingPairsContainingProxy(btBroadphaseProxy* proxy,btDispatcher* dispatcher);
inline bool needsBroadphaseCollision(btBroadphaseProxy* proxy0,btBroadphaseProxy* proxy1) const
{
if (m_overlapFilterCallback)
return m_overlapFilterCallback->needBroadphaseCollision(proxy0,proxy1);
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
return collides;
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
const btBroadphasePairArray& getOverlappingPairArray() const
{
return m_overlappingPairArray;
}
btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
int getNumOverlappingPairs() const
{
return m_overlappingPairArray.size();
}
btOverlapFilterCallback* getOverlapFilterCallback()
{
return m_overlapFilterCallback;
}
void setOverlapFilterCallback(btOverlapFilterCallback* callback)
{
m_overlapFilterCallback = callback;
}
virtual bool hasDeferredRemoval()
{
return m_hasDeferredRemoval;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* ghostPairCallback)
{
m_ghostPairCallback = ghostPairCallback;
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher);
};
///btNullPairCache skips add/removal of overlapping pairs. Userful for benchmarking and unit testing.
class btNullPairCache : public btOverlappingPairCache
{
btBroadphasePairArray m_overlappingPairArray;
public:
virtual btBroadphasePair* getOverlappingPairArrayPtr()
{
return &m_overlappingPairArray[0];
}
const btBroadphasePair* getOverlappingPairArrayPtr() const
{
return &m_overlappingPairArray[0];
}
btBroadphasePairArray& getOverlappingPairArray()
{
return m_overlappingPairArray;
}
virtual void cleanOverlappingPair(btBroadphasePair& /*pair*/,btDispatcher* /*dispatcher*/)
{
}
virtual int getNumOverlappingPairs() const
{
return 0;
}
virtual void cleanProxyFromPairs(btBroadphaseProxy* /*proxy*/,btDispatcher* /*dispatcher*/)
{
}
virtual void setOverlapFilterCallback(btOverlapFilterCallback* /*callback*/)
{
}
virtual void processAllOverlappingPairs(btOverlapCallback*,btDispatcher* /*dispatcher*/)
{
}
virtual btBroadphasePair* findPair(btBroadphaseProxy* /*proxy0*/, btBroadphaseProxy* /*proxy1*/)
{
return 0;
}
virtual bool hasDeferredRemoval()
{
return true;
}
virtual void setInternalGhostPairCallback(btOverlappingPairCallback* /* ghostPairCallback */)
{
}
virtual btBroadphasePair* addOverlappingPair(btBroadphaseProxy* /*proxy0*/,btBroadphaseProxy* /*proxy1*/)
{
return 0;
}
virtual void* removeOverlappingPair(btBroadphaseProxy* /*proxy0*/,btBroadphaseProxy* /*proxy1*/,btDispatcher* /*dispatcher*/)
{
return 0;
}
virtual void removeOverlappingPairsContainingProxy(btBroadphaseProxy* /*proxy0*/,btDispatcher* /*dispatcher*/)
{
}
virtual void sortOverlappingPairs(btDispatcher* dispatcher)
{
(void) dispatcher;
}
};
#endif //BT_OVERLAPPING_PAIR_CACHE_H
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/src/bullet/BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h | #ifndef BT_COLLISION_OBJECT_WRAPPER_H
#define BT_COLLISION_OBJECT_WRAPPER_H
///btCollisionObjectWrapperis an internal data structure.
///Most users can ignore this and use btCollisionObject and btCollisionShape instead
class btCollisionShape;
class btCollisionObject;
class btTransform;
#include "LinearMath/btScalar.h" // for SIMD_FORCE_INLINE definition
#define BT_DECLARE_STACK_ONLY_OBJECT \
private: \
void* operator new(size_t size); \
void operator delete(void*);
struct btCollisionObjectWrapper;
struct btCollisionObjectWrapper
{
BT_DECLARE_STACK_ONLY_OBJECT
private:
btCollisionObjectWrapper(const btCollisionObjectWrapper&); // not implemented. Not allowed.
btCollisionObjectWrapper* operator=(const btCollisionObjectWrapper&);
public:
const btCollisionObjectWrapper* m_parent;
const btCollisionShape* m_shape;
const btCollisionObject* m_collisionObject;
const btTransform& m_worldTransform;
int m_partId;
int m_index;
btCollisionObjectWrapper(const btCollisionObjectWrapper* parent, const btCollisionShape* shape, const btCollisionObject* collisionObject, const btTransform& worldTransform, int partId, int index)
: m_parent(parent), m_shape(shape), m_collisionObject(collisionObject), m_worldTransform(worldTransform),
m_partId(partId), m_index(index)
{}
SIMD_FORCE_INLINE const btTransform& getWorldTransform() const { return m_worldTransform; }
SIMD_FORCE_INLINE const btCollisionObject* getCollisionObject() const { return m_collisionObject; }
SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const { return m_shape; }
};
#endif //BT_COLLISION_OBJECT_WRAPPER_H
| #ifndef BT_COLLISION_OBJECT_WRAPPER_H
#define BT_COLLISION_OBJECT_WRAPPER_H
///btCollisionObjectWrapperis an internal data structure.
///Most users can ignore this and use btCollisionObject and btCollisionShape instead
class btCollisionShape;
class btCollisionObject;
class btTransform;
#include "LinearMath/btScalar.h" // for SIMD_FORCE_INLINE definition
#define BT_DECLARE_STACK_ONLY_OBJECT \
private: \
void* operator new(size_t size); \
void operator delete(void*);
struct btCollisionObjectWrapper;
struct btCollisionObjectWrapper
{
BT_DECLARE_STACK_ONLY_OBJECT
private:
btCollisionObjectWrapper(const btCollisionObjectWrapper&); // not implemented. Not allowed.
btCollisionObjectWrapper* operator=(const btCollisionObjectWrapper&);
public:
const btCollisionObjectWrapper* m_parent;
const btCollisionShape* m_shape;
const btCollisionObject* m_collisionObject;
const btTransform& m_worldTransform;
int m_partId;
int m_index;
btCollisionObjectWrapper(const btCollisionObjectWrapper* parent, const btCollisionShape* shape, const btCollisionObject* collisionObject, const btTransform& worldTransform, int partId, int index)
: m_parent(parent), m_shape(shape), m_collisionObject(collisionObject), m_worldTransform(worldTransform),
m_partId(partId), m_index(index)
{}
SIMD_FORCE_INLINE const btTransform& getWorldTransform() const { return m_worldTransform; }
SIMD_FORCE_INLINE const btCollisionObject* getCollisionObject() const { return m_collisionObject; }
SIMD_FORCE_INLINE const btCollisionShape* getCollisionShape() const { return m_shape; }
};
#endif //BT_COLLISION_OBJECT_WRAPPER_H
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/src/bullet/BulletDynamics/Featherstone/btMultiBodyPoint2Point.h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///This file was written by Erwin Coumans
#ifndef BT_MULTIBODY_POINT2POINT_H
#define BT_MULTIBODY_POINT2POINT_H
#include "btMultiBodyConstraint.h"
//#define BTMBP2PCONSTRAINT_BLOCK_ANGULAR_MOTION_TEST
ATTRIBUTE_ALIGNED16(class) btMultiBodyPoint2Point : public btMultiBodyConstraint
{
protected:
btRigidBody* m_rigidBodyA;
btRigidBody* m_rigidBodyB;
btVector3 m_pivotInA;
btVector3 m_pivotInB;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btMultiBodyPoint2Point(btMultiBody* body, int link, btRigidBody* bodyB, const btVector3& pivotInA, const btVector3& pivotInB);
btMultiBodyPoint2Point(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB);
virtual ~btMultiBodyPoint2Point();
virtual void finalizeMultiDof();
virtual int getIslandIdA() const;
virtual int getIslandIdB() const;
virtual void createConstraintRows(btMultiBodyConstraintArray& constraintRows,
btMultiBodyJacobianData& data,
const btContactSolverInfo& infoGlobal);
const btVector3& getPivotInB() const
{
return m_pivotInB;
}
virtual void setPivotInB(const btVector3& pivotInB)
{
m_pivotInB = pivotInB;
}
virtual void debugDraw(class btIDebugDraw* drawer);
};
#endif //BT_MULTIBODY_POINT2POINT_H
| /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2013 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///This file was written by Erwin Coumans
#ifndef BT_MULTIBODY_POINT2POINT_H
#define BT_MULTIBODY_POINT2POINT_H
#include "btMultiBodyConstraint.h"
//#define BTMBP2PCONSTRAINT_BLOCK_ANGULAR_MOTION_TEST
ATTRIBUTE_ALIGNED16(class) btMultiBodyPoint2Point : public btMultiBodyConstraint
{
protected:
btRigidBody* m_rigidBodyA;
btRigidBody* m_rigidBodyB;
btVector3 m_pivotInA;
btVector3 m_pivotInB;
public:
BT_DECLARE_ALIGNED_ALLOCATOR();
btMultiBodyPoint2Point(btMultiBody* body, int link, btRigidBody* bodyB, const btVector3& pivotInA, const btVector3& pivotInB);
btMultiBodyPoint2Point(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB);
virtual ~btMultiBodyPoint2Point();
virtual void finalizeMultiDof();
virtual int getIslandIdA() const;
virtual int getIslandIdB() const;
virtual void createConstraintRows(btMultiBodyConstraintArray& constraintRows,
btMultiBodyJacobianData& data,
const btContactSolverInfo& infoGlobal);
const btVector3& getPivotInB() const
{
return m_pivotInB;
}
virtual void setPivotInB(const btVector3& pivotInB)
{
m_pivotInB = pivotInB;
}
virtual void debugDraw(class btIDebugDraw* drawer);
};
#endif //BT_MULTIBODY_POINT2POINT_H
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./backends/gdx-backend-robovm-metalangle/src/com/badlogic/gdx/backends/iosrobovm/IOSApplicationConfiguration.java | /*DO NOT EDIT THIS FILE - it is machine generated*/
package com.badlogic.gdx.backends.iosrobovm;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.HdpiMode;
import com.badlogic.gdx.graphics.glutils.HdpiUtils;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.backends.iosrobovm.bindings.metalangle.MGLDrawableColorFormat;
import com.badlogic.gdx.backends.iosrobovm.bindings.metalangle.MGLDrawableDepthFormat;
import com.badlogic.gdx.backends.iosrobovm.bindings.metalangle.MGLDrawableMultisample;
import com.badlogic.gdx.backends.iosrobovm.bindings.metalangle.MGLDrawableStencilFormat;
import org.robovm.apple.uikit.UIRectEdge;
/** DO NOT EDIT THIS FILE - it is machine generated */
public class IOSApplicationConfiguration {
/** whether to enable screen dimming. */
public boolean preventScreenDimming = true;
/** whether or not portrait orientation is supported. */
public boolean orientationPortrait = true;
/** whether or not landscape orientation is supported. */
public boolean orientationLandscape = true;
/** the color format, RGBA8888 is the default * */
public MGLDrawableColorFormat colorFormat = MGLDrawableColorFormat.RGBA8888;
/** the depth buffer format, Format16 is default * */
public MGLDrawableDepthFormat depthFormat = MGLDrawableDepthFormat._16;
/** the stencil buffer format, None is default * */
public MGLDrawableStencilFormat stencilFormat = MGLDrawableStencilFormat.None;
/** the multisample format, None is default * */
public MGLDrawableMultisample multisample = MGLDrawableMultisample.None;
/** preferred/max number of frames per second. Set to "0" to indicate max supported by screen (on standard OpenGL backend (non
* MetalANGLE) Apple has a 60fps cap on most devices). * */
public int preferredFramesPerSecond = 0;
/** whether to use the accelerometer, default true * */
public boolean useAccelerometer = true;
/** the update interval to poll the accelerometer with, in seconds * */
public float accelerometerUpdate = 0.05f;
/** the update interval to poll the magnetometer with, in seconds * */
public float magnetometerUpdate = 0.05f;
/** whether to use the compass, default true * */
public boolean useCompass = true;
/** whether to use the haptics engine, default false. * */
public boolean useHaptics = false;
/** whether or not to allow background music from iPod * */
public boolean allowIpod = true;
/** whether or not the onScreenKeyboard should be closed on return key * */
public boolean keyboardCloseOnReturn = true;
/** Whether to enable OpenGL ES 3 if supported. If not supported it will fall-back to OpenGL ES 2.0. When GL ES 3 is enabled,
* {@link com.badlogic.gdx.Gdx#gl30} can be used to access it's functionality. */
public boolean useGL30 = false;
/** whether the status bar should be visible or not * */
public boolean statusBarVisible = false;
/** whether the home indicator should auto-hide or not. Be careful that if enabled, leaving the app only takes one swipe
* gesture instead of two and the indicator is never semitransparent. * */
public boolean hideHomeIndicator = false;
/** Whether to override the ringer/mute switch, see https://github.com/libgdx/libgdx/issues/4430 */
public boolean overrideRingerSwitch = false;
/** Edges where app gestures must be fired over system gestures. Prior to iOS 11, UIRectEdge.All was default behaviour if
* status bar hidden, see https://github.com/libgdx/libgdx/issues/5110 * */
public UIRectEdge screenEdgesDeferringSystemGestures = UIRectEdge.All;
/** The maximum number of threads to use for network requests. Default is {@link Integer#MAX_VALUE}. */
public int maxNetThreads = Integer.MAX_VALUE;
/** whether to use audio or not. Default is <code>true</code> * */
public boolean useAudio = true;
/** This setting allows you to specify whether you want to work in logical or raw pixel units. See {@link HdpiMode} for more
* information. Note that some OpenGL functions like {@link GL20#glViewport(int, int, int, int)} and
* {@link GL20#glScissor(int, int, int, int)} require raw pixel units. Use {@link HdpiUtils} to help with the conversion if
* HdpiMode is set to {@link HdpiMode#Logical}. Defaults to {@link HdpiMode#Logical}. */
public HdpiMode hdpiMode = HdpiMode.Logical;
ObjectMap<String, IOSDevice> knownDevices = IOSDevice.populateWithKnownDevices();
/** adds device information for newer iOS devices, or overrides information for given ones
* @param classifier human readable device classifier
* @param machineString machine string returned by iOS
* @param ppi device's pixel per inch value */
public void addIosDevice (String classifier, String machineString, int ppi) {
IOSDevice.addDeviceToMap(knownDevices, classifier, machineString, ppi);
}
}
| /*DO NOT EDIT THIS FILE - it is machine generated*/
package com.badlogic.gdx.backends.iosrobovm;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.HdpiMode;
import com.badlogic.gdx.graphics.glutils.HdpiUtils;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.backends.iosrobovm.bindings.metalangle.MGLDrawableColorFormat;
import com.badlogic.gdx.backends.iosrobovm.bindings.metalangle.MGLDrawableDepthFormat;
import com.badlogic.gdx.backends.iosrobovm.bindings.metalangle.MGLDrawableMultisample;
import com.badlogic.gdx.backends.iosrobovm.bindings.metalangle.MGLDrawableStencilFormat;
import org.robovm.apple.uikit.UIRectEdge;
/** DO NOT EDIT THIS FILE - it is machine generated */
public class IOSApplicationConfiguration {
/** whether to enable screen dimming. */
public boolean preventScreenDimming = true;
/** whether or not portrait orientation is supported. */
public boolean orientationPortrait = true;
/** whether or not landscape orientation is supported. */
public boolean orientationLandscape = true;
/** the color format, RGBA8888 is the default * */
public MGLDrawableColorFormat colorFormat = MGLDrawableColorFormat.RGBA8888;
/** the depth buffer format, Format16 is default * */
public MGLDrawableDepthFormat depthFormat = MGLDrawableDepthFormat._16;
/** the stencil buffer format, None is default * */
public MGLDrawableStencilFormat stencilFormat = MGLDrawableStencilFormat.None;
/** the multisample format, None is default * */
public MGLDrawableMultisample multisample = MGLDrawableMultisample.None;
/** preferred/max number of frames per second. Set to "0" to indicate max supported by screen (on standard OpenGL backend (non
* MetalANGLE) Apple has a 60fps cap on most devices). * */
public int preferredFramesPerSecond = 0;
/** whether to use the accelerometer, default true * */
public boolean useAccelerometer = true;
/** the update interval to poll the accelerometer with, in seconds * */
public float accelerometerUpdate = 0.05f;
/** the update interval to poll the magnetometer with, in seconds * */
public float magnetometerUpdate = 0.05f;
/** whether to use the compass, default true * */
public boolean useCompass = true;
/** whether to use the haptics engine, default false. * */
public boolean useHaptics = false;
/** whether or not to allow background music from iPod * */
public boolean allowIpod = true;
/** whether or not the onScreenKeyboard should be closed on return key * */
public boolean keyboardCloseOnReturn = true;
/** Whether to enable OpenGL ES 3 if supported. If not supported it will fall-back to OpenGL ES 2.0. When GL ES 3 is enabled,
* {@link com.badlogic.gdx.Gdx#gl30} can be used to access it's functionality. */
public boolean useGL30 = false;
/** whether the status bar should be visible or not * */
public boolean statusBarVisible = false;
/** whether the home indicator should auto-hide or not. Be careful that if enabled, leaving the app only takes one swipe
* gesture instead of two and the indicator is never semitransparent. * */
public boolean hideHomeIndicator = false;
/** Whether to override the ringer/mute switch, see https://github.com/libgdx/libgdx/issues/4430 */
public boolean overrideRingerSwitch = false;
/** Edges where app gestures must be fired over system gestures. Prior to iOS 11, UIRectEdge.All was default behaviour if
* status bar hidden, see https://github.com/libgdx/libgdx/issues/5110 * */
public UIRectEdge screenEdgesDeferringSystemGestures = UIRectEdge.All;
/** The maximum number of threads to use for network requests. Default is {@link Integer#MAX_VALUE}. */
public int maxNetThreads = Integer.MAX_VALUE;
/** whether to use audio or not. Default is <code>true</code> * */
public boolean useAudio = true;
/** This setting allows you to specify whether you want to work in logical or raw pixel units. See {@link HdpiMode} for more
* information. Note that some OpenGL functions like {@link GL20#glViewport(int, int, int, int)} and
* {@link GL20#glScissor(int, int, int, int)} require raw pixel units. Use {@link HdpiUtils} to help with the conversion if
* HdpiMode is set to {@link HdpiMode#Logical}. Defaults to {@link HdpiMode#Logical}. */
public HdpiMode hdpiMode = HdpiMode.Logical;
ObjectMap<String, IOSDevice> knownDevices = IOSDevice.populateWithKnownDevices();
/** adds device information for newer iOS devices, or overrides information for given ones
* @param classifier human readable device classifier
* @param machineString machine string returned by iOS
* @param ppi device's pixel per inch value */
public void addIosDevice (String classifier, String machineString, int ppi) {
IOSDevice.addDeviceToMap(knownDevices, classifier, machineString, ppi);
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtClipboard.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt;
import com.badlogic.gdx.utils.Clipboard;
/** Basic implementation of clipboard in GWT. Paste only works inside the libGDX application. */
public class GwtClipboard implements Clipboard {
private boolean requestedWritePermissions = false;
private boolean hasWritePermissions = true;
private final ClipboardWriteHandler writeHandler = new ClipboardWriteHandler();
private String content = "";
@Override
public boolean hasContents () {
String contents = getContents();
return contents != null && !contents.isEmpty();
}
@Override
public String getContents () {
return content;
}
@Override
public void setContents (String content) {
this.content = content;
if (requestedWritePermissions || GwtApplication.agentInfo().isFirefox()) {
if (hasWritePermissions) setContentJSNI(content);
} else {
GwtPermissions.queryPermission("clipboard-write", writeHandler);
requestedWritePermissions = true;
}
}
private native void setContentJSNI (String content) /*-{
if ("clipboard" in $wnd.navigator) {
$wnd.navigator.clipboard.writeText(content);
}
}-*/;
private class ClipboardWriteHandler implements GwtPermissions.GwtPermissionResult {
@Override
public void granted () {
hasWritePermissions = true;
setContentJSNI(content);
}
@Override
public void denied () {
hasWritePermissions = false;
}
@Override
public void prompt () {
hasWritePermissions = true;
setContentJSNI(content);
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt;
import com.badlogic.gdx.utils.Clipboard;
/** Basic implementation of clipboard in GWT. Paste only works inside the libGDX application. */
public class GwtClipboard implements Clipboard {
private boolean requestedWritePermissions = false;
private boolean hasWritePermissions = true;
private final ClipboardWriteHandler writeHandler = new ClipboardWriteHandler();
private String content = "";
@Override
public boolean hasContents () {
String contents = getContents();
return contents != null && !contents.isEmpty();
}
@Override
public String getContents () {
return content;
}
@Override
public void setContents (String content) {
this.content = content;
if (requestedWritePermissions || GwtApplication.agentInfo().isFirefox()) {
if (hasWritePermissions) setContentJSNI(content);
} else {
GwtPermissions.queryPermission("clipboard-write", writeHandler);
requestedWritePermissions = true;
}
}
private native void setContentJSNI (String content) /*-{
if ("clipboard" in $wnd.navigator) {
$wnd.navigator.clipboard.writeText(content);
}
}-*/;
private class ClipboardWriteHandler implements GwtPermissions.GwtPermissionResult {
@Override
public void granted () {
hasWritePermissions = true;
setContentJSNI(content);
}
@Override
public void denied () {
hasWritePermissions = false;
}
@Override
public void prompt () {
hasWritePermissions = true;
setContentJSNI(content);
}
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/gles32/GL32DebugControlTest.java | /*******************************************************************************
* Copyright 2022 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.
******************************************************************************/
package com.badlogic.gdx.tests.gles32;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.charset.Charset;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL32;
import com.badlogic.gdx.graphics.GL32.DebugProc;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.GdxTestConfig;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.ScreenUtils;
/** see https://www.khronos.org/opengl/wiki/Debug_Output
*
* @author mgsx */
@GdxTestConfig(requireGL32 = true)
public class GL32DebugControlTest extends GdxTest {
/** Proto utility class for message debug control. */
public static class GLDebug {
/** can only be used when {@link #setCallback(DebugProc)} is set to null. */
private static final DebugReader debugReader = new DebugReader();
/** callback debug message version */
public static final DebugProc loggingCallback = new DebugProc() {
@Override
public void onMessage (int source, int type, int id, int severity, String message) {
GLDebug.log(source, type, id, severity, message);
}
};
private static final int maxMessageLength;
static {
IntBuffer buf = BufferUtils.newIntBuffer(1);
Gdx.gl.glGetIntegerv(GL32.GL_MAX_DEBUG_MESSAGE_LENGTH, buf);
maxMessageLength = buf.get();
// default options
Gdx.gl.glEnable(GL32.GL_DEBUG_OUTPUT_SYNCHRONOUS);
setCallback(loggingCallback);
}
/** polling debug message version */
private static class DebugReader {
int n = 1024;
private IntBuffer sources;
private IntBuffer types;
private IntBuffer ids;
private IntBuffer severities;
private IntBuffer lengths;
private ByteBuffer messageLog;
public DebugReader () {
sources = BufferUtils.newIntBuffer(n);
types = BufferUtils.newIntBuffer(n);
ids = BufferUtils.newIntBuffer(n);
severities = BufferUtils.newIntBuffer(n);
lengths = BufferUtils.newIntBuffer(n);
messageLog = BufferUtils.newByteBuffer(maxMessageLength);
}
public void fetchAndLog () {
for (;;) {
int count = Gdx.gl32.glGetDebugMessageLog(n, sources, types, ids, severities, lengths, messageLog);
if (count == 0) break;
for (int i = 0; i < count; i++) {
int source = sources.get();
int type = types.get();
int id = ids.get();
int severity = severities.get();
int length = lengths.get();
byte[] bytes = new byte[length];
messageLog.get(bytes);
messageLog.rewind();
String message = new String(bytes, Charset.forName("UTF8"));
log(source, type, id, severity, message);
}
sources.rewind();
types.rewind();
ids.rewind();
severities.rewind();
lengths.rewind();
if (count < n) break;
}
}
}
public static void enableOverall (boolean enabled) {
if (enabled) {
Gdx.gl.glEnable(GL32.GL_DEBUG_OUTPUT);
} else {
Gdx.gl.glDisable(GL32.GL_DEBUG_OUTPUT);
}
}
/** set the debug messages callback.
* @param callback when null, messages can be logged using {@link #logPendingMessages()} but some messages may be lost. */
public static void setCallback (DebugProc callback) {
Gdx.gl32.glDebugMessageCallback(callback);
}
public static void insertApplicationMessage (int type, int id, int severity, String message) {
insertMessage(GL32.GL_DEBUG_SOURCE_APPLICATION, type, id, severity, message);
}
public static void insertThirdPartyMessage (int type, int id, int severity, String message) {
insertMessage(GL32.GL_DEBUG_SOURCE_THIRD_PARTY, type, id, severity, message);
}
private static void insertMessage (int source, int type, int id, int severity, String message) {
if (message.length() + 1 > maxMessageLength) {
Gdx.app.error("GLDebug", "user message too long, it will be truncated");
message = message.substring(0, maxMessageLength - 1);
}
Gdx.gl32.glDebugMessageInsert(source, type, id, severity, message);
}
public static void enableAll (boolean enabled) {
enable(enabled, GL32.GL_DONT_CARE, GL32.GL_DONT_CARE, GL32.GL_DONT_CARE);
}
public static void enable (boolean enabled, int source, int type, int severity) {
Gdx.gl32.glDebugMessageControl(source, type, severity, null, enabled);
}
public static void enableIDs (boolean enabled, int source, int type, int... ids) {
IntBuffer idsBuffer = BufferUtils.newIntBuffer(1);
idsBuffer.put(ids);
idsBuffer.flip();
Gdx.gl32.glDebugMessageControl(source, type, GL32.GL_DONT_CARE, idsBuffer, enabled);
}
public static void log (int source, int type, int id, int severity, String message) {
String strSource;
if (source == GL32.GL_DEBUG_SOURCE_APPLICATION) {
strSource = "APPLICATION";
} else if (source == GL32.GL_DEBUG_SOURCE_THIRD_PARTY) {
strSource = "THIRD_PARTY";
} else if (source == GL32.GL_DEBUG_SOURCE_API) {
strSource = "API";
} else if (source == GL32.GL_DEBUG_SOURCE_SHADER_COMPILER) {
strSource = "SHADER_COMPILER";
} else if (source == GL32.GL_DEBUG_SOURCE_WINDOW_SYSTEM) {
strSource = "WINDOW_SYSTEM";
} else if (source == GL32.GL_DEBUG_SOURCE_OTHER) {
strSource = "OTHER";
} else {
strSource = "UNKNOWN";
}
String strType;
if (type == GL32.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR) {
strType = "DEPRECATED_BEHAVIOR";
} else if (type == GL32.GL_DEBUG_TYPE_ERROR) {
strType = "ERROR";
} else if (type == GL32.GL_DEBUG_TYPE_MARKER) {
strType = "MARKER";
} else if (type == GL32.GL_DEBUG_TYPE_OTHER) {
strType = "OTHER";
} else if (type == GL32.GL_DEBUG_TYPE_PERFORMANCE) {
strType = "PERFORMANCE";
} else if (type == GL32.GL_DEBUG_TYPE_POP_GROUP) {
strType = "POP_GROUP";
} else if (type == GL32.GL_DEBUG_TYPE_PORTABILITY) {
strType = "PORTABILITY";
} else if (type == GL32.GL_DEBUG_TYPE_PUSH_GROUP) {
strType = "PUSH_GROUP";
} else if (type == GL32.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR) {
strType = "UNDEFINED_BEHAVIOR";
} else {
strType = "UNKNOWN";
}
String strSeverity;
if (severity == GL32.GL_DEBUG_SEVERITY_HIGH) {
strSeverity = "HIGH";
} else if (severity == GL32.GL_DEBUG_SEVERITY_LOW) {
strSeverity = "LOW";
} else if (severity == GL32.GL_DEBUG_SEVERITY_MEDIUM) {
strSeverity = "MEDIUM";
} else if (severity == GL32.GL_DEBUG_SEVERITY_NOTIFICATION) {
strSeverity = "NOTIFICATION";
} else {
strSeverity = "UNKNOWN";
}
Gdx.app.log("GLDebug",
"source:" + strSource + " type:" + strType + " id:" + id + " severity:" + strSeverity + " message:" + message);
}
public static void logPendingMessages () {
debugReader.fetchAndLog();
}
}
private SpriteBatch batch;
private Texture texture;
private boolean useCallback = true;
private boolean enableNotifications = false;
public void create () {
GLDebug.enableOverall(true);
GLDebug.setCallback(useCallback ? GLDebug.loggingCallback : null);
GLDebug.enableAll(true);
// disable specific message
GLDebug.enableIDs(false, GL32.GL_DEBUG_SOURCE_API, GL32.GL_DEBUG_TYPE_OTHER, 131185);
// insert a user message
GLDebug.insertApplicationMessage(GL32.GL_DEBUG_TYPE_OTHER, 1234, GL32.GL_DEBUG_SEVERITY_NOTIFICATION, "application start");
// generate a fake error (once filtered, once reported)
Gdx.app.log("GDX", "error report disabled");
GLDebug.enableIDs(false, GL32.GL_DEBUG_SOURCE_API, GL32.GL_DEBUG_TYPE_ERROR, GL20.GL_INVALID_OPERATION);
Gdx.gl.glUseProgram(0);
Gdx.gl.glUniform1f(0, 0f);
Gdx.app.log("GDX", "error report enabled");
GLDebug.enableIDs(true, GL32.GL_DEBUG_SOURCE_API, GL32.GL_DEBUG_TYPE_ERROR, GL20.GL_INVALID_OPERATION);
Gdx.gl.glUseProgram(0);
Gdx.gl.glUniform1f(0, 0f);
// reset (enable all but notifications)
GLDebug.enableAll(true);
GLDebug.enable(enableNotifications, GL32.GL_DONT_CARE, GL32.GL_DONT_CARE, GL32.GL_DEBUG_SEVERITY_NOTIFICATION);
texture = new Texture(Gdx.files.internal("data/badlogic.jpg"));
batch = new SpriteBatch();
batch.getProjectionMatrix().setToOrtho2D(0, 0, 1, 1);
// Labeling
Gdx.gl32.glObjectLabel(GL20.GL_TEXTURE, texture.getTextureObjectHandle(), "myTexture");
String label = Gdx.gl32.glGetObjectLabel(GL20.GL_TEXTURE, texture.getTextureObjectHandle());
Gdx.app.log("Debug test", "texture handle " + texture.getTextureObjectHandle() + ": " + label);
// generate fake error
texture.bind();
Gdx.gl.glTexParameteri(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_WRAP_S, -1);
Gdx.gl.glTexParameteri(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_WRAP_S, GL20.GL_CLAMP_TO_EDGE);
}
@Override
public void dispose () {
GLDebug.enableOverall(false);
texture.dispose();
batch.dispose();
}
@Override
public void render () {
// example: enable/disable notifications
if (Gdx.input.justTouched()) {
enableNotifications = !enableNotifications;
GLDebug.enable(enableNotifications, GL32.GL_DONT_CARE, GL32.GL_DONT_CARE, GL32.GL_DEBUG_SEVERITY_NOTIFICATION);
}
ScreenUtils.clear(Color.CLEAR);
Gdx.gl32.glPushDebugGroup(GL32.GL_DEBUG_SOURCE_APPLICATION, 57, "sprite batch drawing 1");
batch.begin();
batch.draw(texture, 0, 0, 1, 1);
batch.end();
Gdx.gl32.glPopDebugGroup();
Gdx.gl32.glPushDebugGroup(GL32.GL_DEBUG_SOURCE_APPLICATION, 57, "sprite batch drawing 2");
batch.begin();
batch.draw(texture, 0, 0, 1, 1);
batch.end();
Gdx.gl32.glPopDebugGroup();
if (!useCallback) {
GLDebug.logPendingMessages();
}
}
}
| /*******************************************************************************
* Copyright 2022 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.
******************************************************************************/
package com.badlogic.gdx.tests.gles32;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.charset.Charset;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL32;
import com.badlogic.gdx.graphics.GL32.DebugProc;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.GdxTestConfig;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.ScreenUtils;
/** see https://www.khronos.org/opengl/wiki/Debug_Output
*
* @author mgsx */
@GdxTestConfig(requireGL32 = true)
public class GL32DebugControlTest extends GdxTest {
/** Proto utility class for message debug control. */
public static class GLDebug {
/** can only be used when {@link #setCallback(DebugProc)} is set to null. */
private static final DebugReader debugReader = new DebugReader();
/** callback debug message version */
public static final DebugProc loggingCallback = new DebugProc() {
@Override
public void onMessage (int source, int type, int id, int severity, String message) {
GLDebug.log(source, type, id, severity, message);
}
};
private static final int maxMessageLength;
static {
IntBuffer buf = BufferUtils.newIntBuffer(1);
Gdx.gl.glGetIntegerv(GL32.GL_MAX_DEBUG_MESSAGE_LENGTH, buf);
maxMessageLength = buf.get();
// default options
Gdx.gl.glEnable(GL32.GL_DEBUG_OUTPUT_SYNCHRONOUS);
setCallback(loggingCallback);
}
/** polling debug message version */
private static class DebugReader {
int n = 1024;
private IntBuffer sources;
private IntBuffer types;
private IntBuffer ids;
private IntBuffer severities;
private IntBuffer lengths;
private ByteBuffer messageLog;
public DebugReader () {
sources = BufferUtils.newIntBuffer(n);
types = BufferUtils.newIntBuffer(n);
ids = BufferUtils.newIntBuffer(n);
severities = BufferUtils.newIntBuffer(n);
lengths = BufferUtils.newIntBuffer(n);
messageLog = BufferUtils.newByteBuffer(maxMessageLength);
}
public void fetchAndLog () {
for (;;) {
int count = Gdx.gl32.glGetDebugMessageLog(n, sources, types, ids, severities, lengths, messageLog);
if (count == 0) break;
for (int i = 0; i < count; i++) {
int source = sources.get();
int type = types.get();
int id = ids.get();
int severity = severities.get();
int length = lengths.get();
byte[] bytes = new byte[length];
messageLog.get(bytes);
messageLog.rewind();
String message = new String(bytes, Charset.forName("UTF8"));
log(source, type, id, severity, message);
}
sources.rewind();
types.rewind();
ids.rewind();
severities.rewind();
lengths.rewind();
if (count < n) break;
}
}
}
public static void enableOverall (boolean enabled) {
if (enabled) {
Gdx.gl.glEnable(GL32.GL_DEBUG_OUTPUT);
} else {
Gdx.gl.glDisable(GL32.GL_DEBUG_OUTPUT);
}
}
/** set the debug messages callback.
* @param callback when null, messages can be logged using {@link #logPendingMessages()} but some messages may be lost. */
public static void setCallback (DebugProc callback) {
Gdx.gl32.glDebugMessageCallback(callback);
}
public static void insertApplicationMessage (int type, int id, int severity, String message) {
insertMessage(GL32.GL_DEBUG_SOURCE_APPLICATION, type, id, severity, message);
}
public static void insertThirdPartyMessage (int type, int id, int severity, String message) {
insertMessage(GL32.GL_DEBUG_SOURCE_THIRD_PARTY, type, id, severity, message);
}
private static void insertMessage (int source, int type, int id, int severity, String message) {
if (message.length() + 1 > maxMessageLength) {
Gdx.app.error("GLDebug", "user message too long, it will be truncated");
message = message.substring(0, maxMessageLength - 1);
}
Gdx.gl32.glDebugMessageInsert(source, type, id, severity, message);
}
public static void enableAll (boolean enabled) {
enable(enabled, GL32.GL_DONT_CARE, GL32.GL_DONT_CARE, GL32.GL_DONT_CARE);
}
public static void enable (boolean enabled, int source, int type, int severity) {
Gdx.gl32.glDebugMessageControl(source, type, severity, null, enabled);
}
public static void enableIDs (boolean enabled, int source, int type, int... ids) {
IntBuffer idsBuffer = BufferUtils.newIntBuffer(1);
idsBuffer.put(ids);
idsBuffer.flip();
Gdx.gl32.glDebugMessageControl(source, type, GL32.GL_DONT_CARE, idsBuffer, enabled);
}
public static void log (int source, int type, int id, int severity, String message) {
String strSource;
if (source == GL32.GL_DEBUG_SOURCE_APPLICATION) {
strSource = "APPLICATION";
} else if (source == GL32.GL_DEBUG_SOURCE_THIRD_PARTY) {
strSource = "THIRD_PARTY";
} else if (source == GL32.GL_DEBUG_SOURCE_API) {
strSource = "API";
} else if (source == GL32.GL_DEBUG_SOURCE_SHADER_COMPILER) {
strSource = "SHADER_COMPILER";
} else if (source == GL32.GL_DEBUG_SOURCE_WINDOW_SYSTEM) {
strSource = "WINDOW_SYSTEM";
} else if (source == GL32.GL_DEBUG_SOURCE_OTHER) {
strSource = "OTHER";
} else {
strSource = "UNKNOWN";
}
String strType;
if (type == GL32.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR) {
strType = "DEPRECATED_BEHAVIOR";
} else if (type == GL32.GL_DEBUG_TYPE_ERROR) {
strType = "ERROR";
} else if (type == GL32.GL_DEBUG_TYPE_MARKER) {
strType = "MARKER";
} else if (type == GL32.GL_DEBUG_TYPE_OTHER) {
strType = "OTHER";
} else if (type == GL32.GL_DEBUG_TYPE_PERFORMANCE) {
strType = "PERFORMANCE";
} else if (type == GL32.GL_DEBUG_TYPE_POP_GROUP) {
strType = "POP_GROUP";
} else if (type == GL32.GL_DEBUG_TYPE_PORTABILITY) {
strType = "PORTABILITY";
} else if (type == GL32.GL_DEBUG_TYPE_PUSH_GROUP) {
strType = "PUSH_GROUP";
} else if (type == GL32.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR) {
strType = "UNDEFINED_BEHAVIOR";
} else {
strType = "UNKNOWN";
}
String strSeverity;
if (severity == GL32.GL_DEBUG_SEVERITY_HIGH) {
strSeverity = "HIGH";
} else if (severity == GL32.GL_DEBUG_SEVERITY_LOW) {
strSeverity = "LOW";
} else if (severity == GL32.GL_DEBUG_SEVERITY_MEDIUM) {
strSeverity = "MEDIUM";
} else if (severity == GL32.GL_DEBUG_SEVERITY_NOTIFICATION) {
strSeverity = "NOTIFICATION";
} else {
strSeverity = "UNKNOWN";
}
Gdx.app.log("GLDebug",
"source:" + strSource + " type:" + strType + " id:" + id + " severity:" + strSeverity + " message:" + message);
}
public static void logPendingMessages () {
debugReader.fetchAndLog();
}
}
private SpriteBatch batch;
private Texture texture;
private boolean useCallback = true;
private boolean enableNotifications = false;
public void create () {
GLDebug.enableOverall(true);
GLDebug.setCallback(useCallback ? GLDebug.loggingCallback : null);
GLDebug.enableAll(true);
// disable specific message
GLDebug.enableIDs(false, GL32.GL_DEBUG_SOURCE_API, GL32.GL_DEBUG_TYPE_OTHER, 131185);
// insert a user message
GLDebug.insertApplicationMessage(GL32.GL_DEBUG_TYPE_OTHER, 1234, GL32.GL_DEBUG_SEVERITY_NOTIFICATION, "application start");
// generate a fake error (once filtered, once reported)
Gdx.app.log("GDX", "error report disabled");
GLDebug.enableIDs(false, GL32.GL_DEBUG_SOURCE_API, GL32.GL_DEBUG_TYPE_ERROR, GL20.GL_INVALID_OPERATION);
Gdx.gl.glUseProgram(0);
Gdx.gl.glUniform1f(0, 0f);
Gdx.app.log("GDX", "error report enabled");
GLDebug.enableIDs(true, GL32.GL_DEBUG_SOURCE_API, GL32.GL_DEBUG_TYPE_ERROR, GL20.GL_INVALID_OPERATION);
Gdx.gl.glUseProgram(0);
Gdx.gl.glUniform1f(0, 0f);
// reset (enable all but notifications)
GLDebug.enableAll(true);
GLDebug.enable(enableNotifications, GL32.GL_DONT_CARE, GL32.GL_DONT_CARE, GL32.GL_DEBUG_SEVERITY_NOTIFICATION);
texture = new Texture(Gdx.files.internal("data/badlogic.jpg"));
batch = new SpriteBatch();
batch.getProjectionMatrix().setToOrtho2D(0, 0, 1, 1);
// Labeling
Gdx.gl32.glObjectLabel(GL20.GL_TEXTURE, texture.getTextureObjectHandle(), "myTexture");
String label = Gdx.gl32.glGetObjectLabel(GL20.GL_TEXTURE, texture.getTextureObjectHandle());
Gdx.app.log("Debug test", "texture handle " + texture.getTextureObjectHandle() + ": " + label);
// generate fake error
texture.bind();
Gdx.gl.glTexParameteri(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_WRAP_S, -1);
Gdx.gl.glTexParameteri(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_WRAP_S, GL20.GL_CLAMP_TO_EDGE);
}
@Override
public void dispose () {
GLDebug.enableOverall(false);
texture.dispose();
batch.dispose();
}
@Override
public void render () {
// example: enable/disable notifications
if (Gdx.input.justTouched()) {
enableNotifications = !enableNotifications;
GLDebug.enable(enableNotifications, GL32.GL_DONT_CARE, GL32.GL_DONT_CARE, GL32.GL_DEBUG_SEVERITY_NOTIFICATION);
}
ScreenUtils.clear(Color.CLEAR);
Gdx.gl32.glPushDebugGroup(GL32.GL_DEBUG_SOURCE_APPLICATION, 57, "sprite batch drawing 1");
batch.begin();
batch.draw(texture, 0, 0, 1, 1);
batch.end();
Gdx.gl32.glPopDebugGroup();
Gdx.gl32.glPushDebugGroup(GL32.GL_DEBUG_SOURCE_APPLICATION, 57, "sprite batch drawing 2");
batch.begin();
batch.draw(texture, 0, 0, 1, 1);
batch.end();
Gdx.gl32.glPopDebugGroup();
if (!useCallback) {
GLDebug.logPendingMessages();
}
}
}
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests-android/assets-raw/skin/default-pane.9.png | PNG
IHDR $IDATxc`@H$$$%CpN t Q) IENDB` | PNG
IHDR $IDATxc`@H$$$%CpN t Q) IENDB` | -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./tests/gdx-tests-android/assets/data/tiles.txt | tiles.png
format: RGBA8888
filter: Linear,Linear
repeat: none
16
rotate: false
xy: 2778, 1102
size: 302, 238
orig: 302, 238
offset: 0, 0
index: -1
02
rotate: false
xy: 2778, 2
size: 274, 391
orig: 274, 391
offset: 0, 0
index: -1
31
rotate: false
xy: 3055, 1342
size: 446, 362
orig: 446, 362
offset: 0, 0
index: -1
09
rotate: false
xy: 2459, 1781
size: 541, 258
orig: 541, 258
offset: 0, 0
index: -1
38
rotate: false
xy: 1751, 2
size: 701, 534
orig: 701, 534
offset: 0, 0
index: -1
24
rotate: false
xy: 3002, 1781
size: 258, 248
orig: 258, 248
offset: 0, 0
index: -1
10
rotate: false
xy: 2760, 395
size: 291, 289
orig: 291, 289
offset: 0, 0
index: -1
17
rotate: false
xy: 2454, 423
size: 302, 238
orig: 302, 238
offset: 0, 0
index: -1
03
rotate: false
xy: 3082, 1061
size: 177, 234
orig: 177, 234
offset: 0, 0
index: -1
32
rotate: false
xy: 1032, 574
size: 183, 160
orig: 183, 160
offset: 0, 0
index: -1
39
rotate: false
xy: 1246, 1390
size: 965, 603
orig: 965, 603
offset: 0, 0
index: -1
25
rotate: false
xy: 3261, 1061
size: 226, 213
orig: 226, 213
offset: 0, 0
index: -1
11
rotate: false
xy: 1217, 574
size: 184, 135
orig: 184, 135
offset: 0, 0
index: -1
40
rotate: false
xy: 1643, 1255
size: 492, 116
orig: 492, 116
offset: 0, 0
index: -1
18
rotate: false
xy: 2454, 205
size: 304, 216
orig: 304, 216
offset: 0, 0
index: -1
04
rotate: false
xy: 3688, 332
size: 171, 357
orig: 171, 357
offset: 0, 0
index: -1
33
rotate: false
xy: 1279, 711
size: 984, 542
orig: 984, 542
offset: 0, 0
index: -1
26
rotate: false
xy: 2137, 1255
size: 308, 108
orig: 308, 108
offset: 0, 0
index: -1
12
rotate: false
xy: 804, 579
size: 160, 178
orig: 160, 178
offset: 0, 0
index: -1
41
rotate: false
xy: 2, 1417
size: 1242, 626
orig: 1242, 626
offset: 0, 0
index: -1
19
rotate: false
xy: 2454, 2
size: 308, 201
orig: 308, 201
offset: 0, 0
index: -1
05
rotate: false
xy: 966, 579
size: 64, 165
orig: 64, 165
offset: 0, 0
index: -1
34
rotate: false
xy: 2213, 1365
size: 840, 414
orig: 840, 414
offset: 0, 0
index: -1
20
rotate: false
xy: 1792, 646
size: 88, 63
orig: 88, 63
offset: 0, 0
index: -1
27
rotate: false
xy: 3460, 1706
size: 226, 190
orig: 226, 190
offset: 0, 0
index: -1
13
rotate: false
xy: 509, 764
size: 768, 624
orig: 768, 624
offset: 0, 0
index: -1
06
rotate: false
xy: 3262, 1706
size: 196, 208
orig: 196, 208
offset: 0, 0
index: -1
35
rotate: false
xy: 2778, 686
size: 118, 414
orig: 256, 512
offset: 78, 30
index: -1
21
rotate: false
xy: 2180, 538
size: 151, 98
orig: 151, 98
offset: 0, 0
index: -1
28
rotate: false
xy: 2213, 1781
size: 244, 264
orig: 244, 264
offset: 0, 0
index: -1
14
rotate: false
xy: 2898, 686
size: 566, 373
orig: 566, 373
offset: 0, 0
index: -1
00
rotate: false
xy: 2, 764
size: 505, 651
orig: 505, 651
offset: 0, 0
index: -1
07
rotate: false
xy: 2180, 638
size: 89, 71
orig: 89, 71
offset: 0, 0
index: -1
36
rotate: false
xy: 1022, 2
size: 727, 570
orig: 727, 570
offset: 0, 0
index: -1
22
rotate: false
xy: 1792, 538
size: 386, 106
orig: 386, 106
offset: 0, 0
index: -1
29
rotate: false
xy: 3054, 332
size: 248, 328
orig: 248, 328
offset: 0, 0
index: -1
15
rotate: false
xy: 2265, 711
size: 511, 485
orig: 511, 485
offset: 0, 0
index: -1
01
rotate: false
xy: 804, 2
size: 216, 575
orig: 216, 575
offset: 0, 0
index: -1
30
rotate: false
xy: 3055, 2
size: 994, 328
orig: 994, 328
offset: 0, 0
index: -1
08
rotate: false
xy: 1279, 1255
size: 362, 130
orig: 362, 130
offset: 0, 0
index: -1
37
rotate: false
xy: 2, 2
size: 800, 760
orig: 800, 760
offset: 0, 0
index: -1
23
rotate: false
xy: 1403, 574
size: 387, 107
orig: 387, 107
offset: 0, 0
index: -1
| tiles.png
format: RGBA8888
filter: Linear,Linear
repeat: none
16
rotate: false
xy: 2778, 1102
size: 302, 238
orig: 302, 238
offset: 0, 0
index: -1
02
rotate: false
xy: 2778, 2
size: 274, 391
orig: 274, 391
offset: 0, 0
index: -1
31
rotate: false
xy: 3055, 1342
size: 446, 362
orig: 446, 362
offset: 0, 0
index: -1
09
rotate: false
xy: 2459, 1781
size: 541, 258
orig: 541, 258
offset: 0, 0
index: -1
38
rotate: false
xy: 1751, 2
size: 701, 534
orig: 701, 534
offset: 0, 0
index: -1
24
rotate: false
xy: 3002, 1781
size: 258, 248
orig: 258, 248
offset: 0, 0
index: -1
10
rotate: false
xy: 2760, 395
size: 291, 289
orig: 291, 289
offset: 0, 0
index: -1
17
rotate: false
xy: 2454, 423
size: 302, 238
orig: 302, 238
offset: 0, 0
index: -1
03
rotate: false
xy: 3082, 1061
size: 177, 234
orig: 177, 234
offset: 0, 0
index: -1
32
rotate: false
xy: 1032, 574
size: 183, 160
orig: 183, 160
offset: 0, 0
index: -1
39
rotate: false
xy: 1246, 1390
size: 965, 603
orig: 965, 603
offset: 0, 0
index: -1
25
rotate: false
xy: 3261, 1061
size: 226, 213
orig: 226, 213
offset: 0, 0
index: -1
11
rotate: false
xy: 1217, 574
size: 184, 135
orig: 184, 135
offset: 0, 0
index: -1
40
rotate: false
xy: 1643, 1255
size: 492, 116
orig: 492, 116
offset: 0, 0
index: -1
18
rotate: false
xy: 2454, 205
size: 304, 216
orig: 304, 216
offset: 0, 0
index: -1
04
rotate: false
xy: 3688, 332
size: 171, 357
orig: 171, 357
offset: 0, 0
index: -1
33
rotate: false
xy: 1279, 711
size: 984, 542
orig: 984, 542
offset: 0, 0
index: -1
26
rotate: false
xy: 2137, 1255
size: 308, 108
orig: 308, 108
offset: 0, 0
index: -1
12
rotate: false
xy: 804, 579
size: 160, 178
orig: 160, 178
offset: 0, 0
index: -1
41
rotate: false
xy: 2, 1417
size: 1242, 626
orig: 1242, 626
offset: 0, 0
index: -1
19
rotate: false
xy: 2454, 2
size: 308, 201
orig: 308, 201
offset: 0, 0
index: -1
05
rotate: false
xy: 966, 579
size: 64, 165
orig: 64, 165
offset: 0, 0
index: -1
34
rotate: false
xy: 2213, 1365
size: 840, 414
orig: 840, 414
offset: 0, 0
index: -1
20
rotate: false
xy: 1792, 646
size: 88, 63
orig: 88, 63
offset: 0, 0
index: -1
27
rotate: false
xy: 3460, 1706
size: 226, 190
orig: 226, 190
offset: 0, 0
index: -1
13
rotate: false
xy: 509, 764
size: 768, 624
orig: 768, 624
offset: 0, 0
index: -1
06
rotate: false
xy: 3262, 1706
size: 196, 208
orig: 196, 208
offset: 0, 0
index: -1
35
rotate: false
xy: 2778, 686
size: 118, 414
orig: 256, 512
offset: 78, 30
index: -1
21
rotate: false
xy: 2180, 538
size: 151, 98
orig: 151, 98
offset: 0, 0
index: -1
28
rotate: false
xy: 2213, 1781
size: 244, 264
orig: 244, 264
offset: 0, 0
index: -1
14
rotate: false
xy: 2898, 686
size: 566, 373
orig: 566, 373
offset: 0, 0
index: -1
00
rotate: false
xy: 2, 764
size: 505, 651
orig: 505, 651
offset: 0, 0
index: -1
07
rotate: false
xy: 2180, 638
size: 89, 71
orig: 89, 71
offset: 0, 0
index: -1
36
rotate: false
xy: 1022, 2
size: 727, 570
orig: 727, 570
offset: 0, 0
index: -1
22
rotate: false
xy: 1792, 538
size: 386, 106
orig: 386, 106
offset: 0, 0
index: -1
29
rotate: false
xy: 3054, 332
size: 248, 328
orig: 248, 328
offset: 0, 0
index: -1
15
rotate: false
xy: 2265, 711
size: 511, 485
orig: 511, 485
offset: 0, 0
index: -1
01
rotate: false
xy: 804, 2
size: 216, 575
orig: 216, 575
offset: 0, 0
index: -1
30
rotate: false
xy: 3055, 2
size: 994, 328
orig: 994, 328
offset: 0, 0
index: -1
08
rotate: false
xy: 1279, 1255
size: 362, 130
orig: 362, 130
offset: 0, 0
index: -1
37
rotate: false
xy: 2, 2
size: 800, 760
orig: 800, 760
offset: 0, 0
index: -1
23
rotate: false
xy: 1403, 574
size: 387, 107
orig: 387, 107
offset: 0, 0
index: -1
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-setup/res/com/badlogic/gdx/setup/resources/android/res/values-v21/styles.xml | <?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="android:Theme.Material.Light.NoActionBar.Fullscreen">
<item name="android:colorBackground">@color/ic_background_color</item>
</style>
</resources>
| <?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="android:Theme.Material.Light.NoActionBar.Fullscreen">
<item name="android:colorBackground">@color/ic_background_color</item>
</style>
</resources>
| -1 |
libgdx/libgdx | 7,311 | Set GdxSetup source level to java 8 | Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | obigu | "2023-12-28T13:24:30Z" | "2023-12-28T19:35:04Z" | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | 449619e48dc25ce335c4003830e409aa69f5f3f7 | Set GdxSetup source level to java 8. Since Java 21 (LTS) is the default version when downloading java, many users (specially new libGDX users) are complaining new projects don't work. Even if libGDX iOS backend doesn't fully support Java 8 language features (see https://github.com/libgdx/libgdx/issues/5487) at this point I think, until we decide on the approach to move forward, we should change Gdx Setup source level to 8 on all modules. | ./extensions/gdx-bullet/jni/swig-src/softbody/com/badlogic/gdx/physics/bullet/softbody/SWIGTYPE_p_btAlignedObjectArrayT_int_t.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.softbody;
public class SWIGTYPE_p_btAlignedObjectArrayT_int_t {
private transient long swigCPtr;
protected SWIGTYPE_p_btAlignedObjectArrayT_int_t (long cPtr, @SuppressWarnings("unused") boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_btAlignedObjectArrayT_int_t () {
swigCPtr = 0;
}
protected static long getCPtr (SWIGTYPE_p_btAlignedObjectArrayT_int_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.softbody;
public class SWIGTYPE_p_btAlignedObjectArrayT_int_t {
private transient long swigCPtr;
protected SWIGTYPE_p_btAlignedObjectArrayT_int_t (long cPtr, @SuppressWarnings("unused") boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_btAlignedObjectArrayT_int_t () {
swigCPtr = 0;
}
protected static long getCPtr (SWIGTYPE_p_btAlignedObjectArrayT_int_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.utils.*;
/** An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class.
* In the {@link Activity#onCreate(Bundle)} method call the {@link #initialize(ApplicationListener)} method specifying the
* configuration for the GLSurfaceView.
*
* @author mzechner */
public class AndroidApplication extends Activity implements AndroidApplicationBase {
protected AndroidGraphics graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected AndroidClipboard clipboard;
protected ApplicationListener listener;
public Handler handler;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected final SnapshotArray<LifecycleListener> lifecycleListeners = new SnapshotArray<LifecycleListener>(
LifecycleListener.class);
private final Array<AndroidEventListener> androidEventListeners = new Array<AndroidEventListener>();
protected int logLevel = LOG_INFO;
protected ApplicationLogger applicationLogger;
protected boolean useImmersiveMode = false;
private int wasFocusChanged = -1;
private boolean isWaitingForAudio = false;
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
*
* @param listener the {@link ApplicationListener} implementing the program logic **/
public void initialize (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(listener, config);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. You can configure other aspects of the application with the rest of the fields in the
* {@link AndroidApplicationConfiguration} instance.
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.). */
public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) {
init(listener, config, false);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
* <p>
* Note: you have to add the returned view to your layout!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
return initializeForView(listener, config);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. You can configure other aspects of the application with the rest of the fields in the
* {@link AndroidApplicationConfiguration} instance.
* <p>
* Note: you have to add the returned view to your layout!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.).
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) {
init(listener, config, true);
return graphics.getView();
}
private void init (ApplicationListener listener, AndroidApplicationConfiguration config, boolean isForView) {
if (this.getVersion() < MINIMUM_SDK) {
throw new GdxRuntimeException("libGDX requires Android API Level " + MINIMUM_SDK + " or later.");
}
config.nativeLoader.load();
setApplicationLogger(new AndroidApplicationLogger());
graphics = new AndroidGraphics(this, config,
config.resolutionStrategy == null ? new FillResolutionStrategy() : config.resolutionStrategy);
input = createInput(this, this, graphics.view, config);
audio = createAudio(this, config);
files = createFiles();
net = new AndroidNet(this, config);
this.listener = listener;
this.handler = new Handler();
this.useImmersiveMode = config.useImmersiveMode;
this.clipboard = new AndroidClipboard(this);
// Add a specialized audio lifecycle listener
addLifecycleListener(new LifecycleListener() {
@Override
public void resume () {
// No need to resume audio here
}
@Override
public void pause () {
audio.pause();
}
@Override
public void dispose () {
audio.dispose();
}
});
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
if (!isForView) {
try {
requestWindowFeature(Window.FEATURE_NO_TITLE);
} catch (Exception ex) {
log("AndroidApplication", "Content already displayed, cannot request FEATURE_NO_TITLE", ex);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
setContentView(graphics.getView(), createLayoutParams());
}
createWakeLock(config.useWakelock);
useImmersiveMode(this.useImmersiveMode);
if (this.useImmersiveMode && getVersion() >= Build.VERSION_CODES.KITKAT) {
AndroidVisibilityListener vlistener = new AndroidVisibilityListener();
vlistener.createListener(this);
}
// detect an already connected bluetooth keyboardAvailable
if (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS) input.setKeyboardAvailable(true);
}
protected FrameLayout.LayoutParams createLayoutParams () {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void createWakeLock (boolean use) {
if (use) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@Override
public void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
useImmersiveMode(this.useImmersiveMode);
if (hasFocus) {
this.wasFocusChanged = 1;
if (this.isWaitingForAudio) {
this.audio.resume();
this.isWaitingForAudio = false;
}
} else {
this.wasFocusChanged = 0;
}
}
@TargetApi(19)
@Override
public void useImmersiveMode (boolean use) {
if (!use || getVersion() < Build.VERSION_CODES.KITKAT) return;
View view = getWindow().getDecorView();
int code = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
view.setSystemUiVisibility(code);
}
@Override
protected void onPause () {
boolean isContinuous = graphics.isContinuousRendering();
boolean isContinuousEnforced = AndroidGraphics.enforceContinuousRendering;
// from here we don't want non continuous rendering
AndroidGraphics.enforceContinuousRendering = true;
graphics.setContinuousRendering(true);
// calls to setContinuousRendering(false) from other thread (ex: GLThread)
// will be ignored at this point...
graphics.pause();
input.onPause();
if (isFinishing()) {
graphics.clearManagedCaches();
graphics.destroy();
}
AndroidGraphics.enforceContinuousRendering = isContinuousEnforced;
graphics.setContinuousRendering(isContinuous);
graphics.onPauseGLSurfaceView();
super.onPause();
}
@Override
protected void onResume () {
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
input.onResume();
if (graphics != null) {
graphics.onResumeGLSurfaceView();
}
if (!firstResume) {
graphics.resume();
} else
firstResume = false;
this.isWaitingForAudio = true;
if (this.wasFocusChanged == 1 || this.wasFocusChanged == -1) {
this.audio.resume();
this.isWaitingForAudio = false;
}
super.onResume();
}
@Override
protected void onDestroy () {
super.onDestroy();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public AndroidInput getInput () {
return input;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
@Override
public int getVersion () {
return android.os.Build.VERSION.SDK_INT;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(getSharedPreferences(name, Context.MODE_PRIVATE));
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
@Override
public void onConfigurationChanged (Configuration config) {
super.onConfigurationChanged(config);
boolean keyboardAvailable = false;
if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true;
input.setKeyboardAvailable(keyboardAvailable);
}
@Override
public void exit () {
handler.post(new Runnable() {
@Override
public void run () {
AndroidApplication.this.finish();
}
});
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// forward events to our listeners if there are any installed
synchronized (androidEventListeners) {
for (int i = 0; i < androidEventListeners.size; i++) {
androidEventListeners.get(i).onActivityResult(requestCode, resultCode, data);
}
}
}
/** Adds an event listener for Android specific event such as onActivityResult(...). */
public void addAndroidEventListener (AndroidEventListener listener) {
synchronized (androidEventListeners) {
androidEventListeners.add(listener);
}
}
/** Removes an event listener for Android specific event such as onActivityResult(...). */
public void removeAndroidEventListener (AndroidEventListener listener) {
synchronized (androidEventListeners) {
androidEventListeners.removeValue(listener, true);
}
}
@Override
public Context getContext () {
return this;
}
@Override
public Array<Runnable> getRunnables () {
return runnables;
}
@Override
public Array<Runnable> getExecutedRunnables () {
return executedRunnables;
}
@Override
public SnapshotArray<LifecycleListener> getLifecycleListeners () {
return lifecycleListeners;
}
@Override
public Window getApplicationWindow () {
return this.getWindow();
}
@Override
public Handler getHandler () {
return this.handler;
}
@Override
public AndroidAudio createAudio (Context context, AndroidApplicationConfiguration config) {
return new DefaultAndroidAudio(context, config);
}
@Override
public AndroidInput createInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
return new DefaultAndroidInput(this, this, graphics.view, config);
}
protected AndroidFiles createFiles () {
this.getFilesDir(); // workaround for Android bug #10515463
return new DefaultAndroidFiles(this.getAssets(), this, true);
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.utils.*;
/** An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class.
* In the {@link Activity#onCreate(Bundle)} method call the {@link #initialize(ApplicationListener)} method specifying the
* configuration for the GLSurfaceView.
*
* @author mzechner */
public class AndroidApplication extends Activity implements AndroidApplicationBase {
protected AndroidGraphics graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected AndroidClipboard clipboard;
protected ApplicationListener listener;
public Handler handler;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected final SnapshotArray<LifecycleListener> lifecycleListeners = new SnapshotArray<LifecycleListener>(
LifecycleListener.class);
private final Array<AndroidEventListener> androidEventListeners = new Array<AndroidEventListener>();
protected int logLevel = LOG_INFO;
protected ApplicationLogger applicationLogger;
protected boolean useImmersiveMode = false;
private int wasFocusChanged = -1;
private boolean isWaitingForAudio = false;
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
*
* @param listener the {@link ApplicationListener} implementing the program logic **/
public void initialize (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(listener, config);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. You can configure other aspects of the application with the rest of the fields in the
* {@link AndroidApplicationConfiguration} instance.
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.). */
public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) {
init(listener, config, false);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
* <p>
* Note: you have to add the returned view to your layout!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
return initializeForView(listener, config);
}
/** This method has to be called in the {@link Activity#onCreate(Bundle)} method. It sets up all the things necessary to get
* input, render via OpenGL and so on. You can configure other aspects of the application with the rest of the fields in the
* {@link AndroidApplicationConfiguration} instance.
* <p>
* Note: you have to add the returned view to your layout!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.).
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) {
init(listener, config, true);
return graphics.getView();
}
private void init (ApplicationListener listener, AndroidApplicationConfiguration config, boolean isForView) {
if (this.getVersion() < MINIMUM_SDK) {
throw new GdxRuntimeException("libGDX requires Android API Level " + MINIMUM_SDK + " or later.");
}
config.nativeLoader.load();
setApplicationLogger(new AndroidApplicationLogger());
graphics = new AndroidGraphics(this, config,
config.resolutionStrategy == null ? new FillResolutionStrategy() : config.resolutionStrategy);
input = createInput(this, this, graphics.view, config);
audio = createAudio(this, config);
files = createFiles();
net = new AndroidNet(this, config);
this.listener = listener;
this.handler = new Handler();
this.useImmersiveMode = config.useImmersiveMode;
this.clipboard = new AndroidClipboard(this);
// Add a specialized audio lifecycle listener
addLifecycleListener(new LifecycleListener() {
@Override
public void resume () {
// No need to resume audio here
}
@Override
public void pause () {
audio.pause();
}
@Override
public void dispose () {
audio.dispose();
}
});
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
if (!isForView) {
try {
requestWindowFeature(Window.FEATURE_NO_TITLE);
} catch (Exception ex) {
log("AndroidApplication", "Content already displayed, cannot request FEATURE_NO_TITLE", ex);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
setContentView(graphics.getView(), createLayoutParams());
}
createWakeLock(config.useWakelock);
useImmersiveMode(this.useImmersiveMode);
if (this.useImmersiveMode && getVersion() >= Build.VERSION_CODES.KITKAT) {
AndroidVisibilityListener vlistener = new AndroidVisibilityListener();
vlistener.createListener(this);
}
// detect an already connected bluetooth keyboardAvailable
if (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS) input.setKeyboardAvailable(true);
}
protected FrameLayout.LayoutParams createLayoutParams () {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void createWakeLock (boolean use) {
if (use) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@Override
public void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
useImmersiveMode(this.useImmersiveMode);
if (hasFocus) {
this.wasFocusChanged = 1;
if (this.isWaitingForAudio) {
this.audio.resume();
this.isWaitingForAudio = false;
}
} else {
this.wasFocusChanged = 0;
}
}
@TargetApi(19)
@Override
public void useImmersiveMode (boolean use) {
if (!use || getVersion() < Build.VERSION_CODES.KITKAT) return;
View view = getWindow().getDecorView();
int code = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
view.setSystemUiVisibility(code);
}
@Override
protected void onPause () {
boolean isContinuous = graphics.isContinuousRendering();
boolean isContinuousEnforced = AndroidGraphics.enforceContinuousRendering;
// from here we don't want non continuous rendering
AndroidGraphics.enforceContinuousRendering = true;
graphics.setContinuousRendering(true);
// calls to setContinuousRendering(false) from other thread (ex: GLThread)
// will be ignored at this point...
graphics.pause();
input.onPause();
if (isFinishing()) {
graphics.clearManagedCaches();
graphics.destroy();
}
AndroidGraphics.enforceContinuousRendering = isContinuousEnforced;
graphics.setContinuousRendering(isContinuous);
graphics.onPauseGLSurfaceView();
super.onPause();
}
@Override
protected void onResume () {
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
input.onResume();
if (graphics != null) {
graphics.onResumeGLSurfaceView();
}
if (!firstResume) {
graphics.resume();
} else
firstResume = false;
this.isWaitingForAudio = true;
if (this.wasFocusChanged == 1 || this.wasFocusChanged == -1) {
this.audio.resume();
this.isWaitingForAudio = false;
}
super.onResume();
}
@Override
protected void onDestroy () {
super.onDestroy();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public AndroidInput getInput () {
return input;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
@Override
public int getVersion () {
return android.os.Build.VERSION.SDK_INT;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(getSharedPreferences(name, Context.MODE_PRIVATE));
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
@Override
public void onConfigurationChanged (Configuration config) {
super.onConfigurationChanged(config);
boolean keyboardAvailable = false;
if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true;
input.setKeyboardAvailable(keyboardAvailable);
}
@Override
public void exit () {
handler.post(new Runnable() {
@Override
public void run () {
AndroidApplication.this.finish();
}
});
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// forward events to our listeners if there are any installed
synchronized (androidEventListeners) {
for (int i = 0; i < androidEventListeners.size; i++) {
androidEventListeners.get(i).onActivityResult(requestCode, resultCode, data);
}
}
}
/** Adds an event listener for Android specific event such as onActivityResult(...). */
public void addAndroidEventListener (AndroidEventListener listener) {
synchronized (androidEventListeners) {
androidEventListeners.add(listener);
}
}
/** Removes an event listener for Android specific event such as onActivityResult(...). */
public void removeAndroidEventListener (AndroidEventListener listener) {
synchronized (androidEventListeners) {
androidEventListeners.removeValue(listener, true);
}
}
@Override
public Context getContext () {
return this;
}
@Override
public Array<Runnable> getRunnables () {
return runnables;
}
@Override
public Array<Runnable> getExecutedRunnables () {
return executedRunnables;
}
@Override
public SnapshotArray<LifecycleListener> getLifecycleListeners () {
return lifecycleListeners;
}
@Override
public Window getApplicationWindow () {
return this.getWindow();
}
@Override
public Handler getHandler () {
return this.handler;
}
@Override
public AndroidAudio createAudio (Context context, AndroidApplicationConfiguration config) {
if (!config.disableAudio)
return new DefaultAndroidAudio(context, config);
else
return new DisabledAndroidAudio();
}
@Override
public AndroidInput createInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
return new DefaultAndroidInput(this, this, graphics.view, config);
}
protected AndroidFiles createFiles () {
this.getFilesDir(); // workaround for Android bug #10515463
return new DefaultAndroidFiles(this.getAssets(), this, true);
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidDaydream.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Debug;
import android.os.Handler;
import android.os.Looper;
import android.service.dreams.DreamService;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
import com.badlogic.gdx.utils.GdxNativesLoader;
import com.badlogic.gdx.utils.SnapshotArray;
/** An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class.
* In the Activity#onCreate(Bundle) method call the {@link #initialize(ApplicationListener)} method specifying the configuration
* for the {@link GLSurfaceView}.
*
* @author mzechner */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public class AndroidDaydream extends DreamService implements AndroidApplicationBase {
protected AndroidGraphics graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected AndroidClipboard clipboard;
protected ApplicationListener listener;
protected Handler handler;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected final SnapshotArray<LifecycleListener> lifecycleListeners = new SnapshotArray<LifecycleListener>(
LifecycleListener.class);
protected int logLevel = LOG_INFO;
protected ApplicationLogger applicationLogger;
/** This method has to be called in the Activity#onCreate(Bundle) method. It sets up all the things necessary to get input,
* render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
* @param listener the {@link ApplicationListener} implementing the program logic */
public void initialize (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(listener, config);
}
/** This method has to be called in the Activity#onCreate(Bundle) method. It sets up all the things necessary to get input,
* render via OpenGL and so on. You can configure other aspects of the application with the rest of the fields in the
* {@link AndroidApplicationConfiguration} instance.
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.). */
public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) {
init(listener, config, false);
}
/** This method has to be called in the Activity#onCreate(Bundle) method. It sets up all the things necessary to get input,
* render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
* <p>
* Note: you have to add the returned view to your layout!
* @param listener the {@link ApplicationListener} implementing the program logic
* @return the {@link GLSurfaceView} of the application */
public View initializeForView (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
return initializeForView(listener, config);
}
/** This method has to be called in the Activity#onCreate(Bundle) method. It sets up all the things necessary to get input,
* render via OpenGL and so on. You can configure other aspects of the application with the rest of the fields in the
* {@link AndroidApplicationConfiguration} instance.
* <p>
* Note: you have to add the returned view to your layout!
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.).
* @return the {@link GLSurfaceView} of the application */
public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) {
init(listener, config, true);
return graphics.getView();
}
private void init (ApplicationListener listener, AndroidApplicationConfiguration config, boolean isForView) {
GdxNativesLoader.load();
setApplicationLogger(new AndroidApplicationLogger());
graphics = new AndroidGraphics(this, config,
config.resolutionStrategy == null ? new FillResolutionStrategy() : config.resolutionStrategy);
input = createInput(this, this, graphics.view, config);
audio = createAudio(this, config);
files = createFiles();
net = new AndroidNet(this, config);
this.listener = listener;
this.handler = new Handler();
this.clipboard = new AndroidClipboard(this);
// Add a specialized audio lifecycle listener
addLifecycleListener(new LifecycleListener() {
@Override
public void resume () {
audio.resume();
}
@Override
public void pause () {
audio.pause();
}
@Override
public void dispose () {
audio.dispose();
audio = null;
}
});
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
if (!isForView) {
setFullscreen(true);
setContentView(graphics.getView(), createLayoutParams());
}
createWakeLock(config.useWakelock);
// detect an already connected bluetooth keyboardAvailable
if (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS) input.setKeyboardAvailable(true);
}
protected FrameLayout.LayoutParams createLayoutParams () {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void createWakeLock (boolean use) {
if (use) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@Override
public void onDreamingStopped () {
boolean isContinuous = graphics.isContinuousRendering();
graphics.setContinuousRendering(true);
graphics.pause();
input.onDreamingStopped();
graphics.clearManagedCaches();
graphics.destroy();
graphics.setContinuousRendering(isContinuous);
graphics.onPauseGLSurfaceView();
super.onDreamingStopped();
}
@Override
public void onDreamingStarted () {
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
input.onDreamingStarted();
if (graphics != null) {
graphics.onResumeGLSurfaceView();
}
if (!firstResume) {
graphics.resume();
} else
firstResume = false;
super.onDreamingStarted();
}
@Override
public void onDetachedFromWindow () {
super.onDetachedFromWindow();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public AndroidInput getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
@Override
public int getVersion () {
return android.os.Build.VERSION.SDK_INT;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(getSharedPreferences(name, Context.MODE_PRIVATE));
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
@Override
public void onConfigurationChanged (Configuration config) {
super.onConfigurationChanged(config);
boolean keyboardAvailable = false;
if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true;
input.setKeyboardAvailable(keyboardAvailable);
}
@Override
public void exit () {
handler.post(new Runnable() {
@Override
public void run () {
AndroidDaydream.this.finish();
}
});
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
public Context getContext () {
return this;
}
@Override
public Array<Runnable> getRunnables () {
return runnables;
}
@Override
public Array<Runnable> getExecutedRunnables () {
return executedRunnables;
}
@Override
public SnapshotArray<LifecycleListener> getLifecycleListeners () {
return lifecycleListeners;
}
@Override
public Window getApplicationWindow () {
return this.getWindow();
}
@Override
public Handler getHandler () {
return this.handler;
}
@Override
public AndroidAudio createAudio (Context context, AndroidApplicationConfiguration config) {
return new DefaultAndroidAudio(context, config);
}
@Override
public AndroidInput createInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
return new DefaultAndroidInput(this, this, graphics.view, config);
}
protected AndroidFiles createFiles () {
this.getFilesDir(); // workaround for Android bug #10515463
return new DefaultAndroidFiles(this.getAssets(), this, true);
}
@Override
public void runOnUiThread (Runnable runnable) {
if (Looper.myLooper() != Looper.getMainLooper()) {
// The current thread is not the UI thread.
// Let's post the runnable to the event queue of the UI thread.
new Handler(Looper.getMainLooper()).post(runnable);
} else {
// The current thread is the UI thread already.
// Let's execute the runnable immediately.
runnable.run();
}
}
@Override
public void useImmersiveMode (boolean b) {
throw new UnsupportedOperationException();
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Debug;
import android.os.Handler;
import android.os.Looper;
import android.service.dreams.DreamService;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
import com.badlogic.gdx.utils.GdxNativesLoader;
import com.badlogic.gdx.utils.SnapshotArray;
/** An implementation of the {@link Application} interface for Android. Create an {@link Activity} that derives from this class.
* In the Activity#onCreate(Bundle) method call the {@link #initialize(ApplicationListener)} method specifying the configuration
* for the {@link GLSurfaceView}.
*
* @author mzechner */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public class AndroidDaydream extends DreamService implements AndroidApplicationBase {
protected AndroidGraphics graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected AndroidClipboard clipboard;
protected ApplicationListener listener;
protected Handler handler;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected final SnapshotArray<LifecycleListener> lifecycleListeners = new SnapshotArray<LifecycleListener>(
LifecycleListener.class);
protected int logLevel = LOG_INFO;
protected ApplicationLogger applicationLogger;
/** This method has to be called in the Activity#onCreate(Bundle) method. It sets up all the things necessary to get input,
* render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
* @param listener the {@link ApplicationListener} implementing the program logic */
public void initialize (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(listener, config);
}
/** This method has to be called in the Activity#onCreate(Bundle) method. It sets up all the things necessary to get input,
* render via OpenGL and so on. You can configure other aspects of the application with the rest of the fields in the
* {@link AndroidApplicationConfiguration} instance.
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.). */
public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) {
init(listener, config, false);
}
/** This method has to be called in the Activity#onCreate(Bundle) method. It sets up all the things necessary to get input,
* render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
* <p>
* Note: you have to add the returned view to your layout!
* @param listener the {@link ApplicationListener} implementing the program logic
* @return the {@link GLSurfaceView} of the application */
public View initializeForView (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
return initializeForView(listener, config);
}
/** This method has to be called in the Activity#onCreate(Bundle) method. It sets up all the things necessary to get input,
* render via OpenGL and so on. You can configure other aspects of the application with the rest of the fields in the
* {@link AndroidApplicationConfiguration} instance.
* <p>
* Note: you have to add the returned view to your layout!
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.).
* @return the {@link GLSurfaceView} of the application */
public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) {
init(listener, config, true);
return graphics.getView();
}
private void init (ApplicationListener listener, AndroidApplicationConfiguration config, boolean isForView) {
GdxNativesLoader.load();
setApplicationLogger(new AndroidApplicationLogger());
graphics = new AndroidGraphics(this, config,
config.resolutionStrategy == null ? new FillResolutionStrategy() : config.resolutionStrategy);
input = createInput(this, this, graphics.view, config);
audio = createAudio(this, config);
files = createFiles();
net = new AndroidNet(this, config);
this.listener = listener;
this.handler = new Handler();
this.clipboard = new AndroidClipboard(this);
// Add a specialized audio lifecycle listener
addLifecycleListener(new LifecycleListener() {
@Override
public void resume () {
audio.resume();
}
@Override
public void pause () {
audio.pause();
}
@Override
public void dispose () {
audio.dispose();
audio = null;
}
});
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
if (!isForView) {
setFullscreen(true);
setContentView(graphics.getView(), createLayoutParams());
}
createWakeLock(config.useWakelock);
// detect an already connected bluetooth keyboardAvailable
if (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS) input.setKeyboardAvailable(true);
}
protected FrameLayout.LayoutParams createLayoutParams () {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void createWakeLock (boolean use) {
if (use) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@Override
public void onDreamingStopped () {
boolean isContinuous = graphics.isContinuousRendering();
graphics.setContinuousRendering(true);
graphics.pause();
input.onDreamingStopped();
graphics.clearManagedCaches();
graphics.destroy();
graphics.setContinuousRendering(isContinuous);
graphics.onPauseGLSurfaceView();
super.onDreamingStopped();
}
@Override
public void onDreamingStarted () {
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
input.onDreamingStarted();
if (graphics != null) {
graphics.onResumeGLSurfaceView();
}
if (!firstResume) {
graphics.resume();
} else
firstResume = false;
super.onDreamingStarted();
}
@Override
public void onDetachedFromWindow () {
super.onDetachedFromWindow();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public AndroidInput getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
@Override
public int getVersion () {
return android.os.Build.VERSION.SDK_INT;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(getSharedPreferences(name, Context.MODE_PRIVATE));
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
@Override
public void onConfigurationChanged (Configuration config) {
super.onConfigurationChanged(config);
boolean keyboardAvailable = false;
if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true;
input.setKeyboardAvailable(keyboardAvailable);
}
@Override
public void exit () {
handler.post(new Runnable() {
@Override
public void run () {
AndroidDaydream.this.finish();
}
});
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
public Context getContext () {
return this;
}
@Override
public Array<Runnable> getRunnables () {
return runnables;
}
@Override
public Array<Runnable> getExecutedRunnables () {
return executedRunnables;
}
@Override
public SnapshotArray<LifecycleListener> getLifecycleListeners () {
return lifecycleListeners;
}
@Override
public Window getApplicationWindow () {
return this.getWindow();
}
@Override
public Handler getHandler () {
return this.handler;
}
@Override
public AndroidAudio createAudio (Context context, AndroidApplicationConfiguration config) {
if (!config.disableAudio)
return new DefaultAndroidAudio(context, config);
else
return new DisabledAndroidAudio();
}
@Override
public AndroidInput createInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
return new DefaultAndroidInput(this, this, graphics.view, config);
}
protected AndroidFiles createFiles () {
this.getFilesDir(); // workaround for Android bug #10515463
return new DefaultAndroidFiles(this.getAssets(), this, true);
}
@Override
public void runOnUiThread (Runnable runnable) {
if (Looper.myLooper() != Looper.getMainLooper()) {
// The current thread is not the UI thread.
// Let's post the runnable to the event queue of the UI thread.
new Handler(Looper.getMainLooper()).post(runnable);
} else {
// The current thread is the UI thread already.
// Let's execute the runnable immediately.
runnable.run();
}
}
@Override
public void useImmersiveMode (boolean b) {
throw new UnsupportedOperationException();
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidFragmentApplication.java |
package com.badlogic.gdx.backends.android;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Debug;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import androidx.fragment.app.Fragment;
import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.utils.*;
/** Implementation of the {@link AndroidApplicationBase} that is based on the {@link Fragment} class. This class is similar in use
* to the {@link AndroidApplication} class, which is based on an {@link Activity}.
*
* @author Bartol Karuza ([email protected]) */
public class AndroidFragmentApplication extends Fragment implements AndroidApplicationBase {
/** Callbacks interface for letting the fragment interact with the Activitiy, parent fragment or target fragment.
*
* @author Bartol Karuza ([email protected]) */
public interface Callbacks {
void exit ();
}
protected AndroidGraphics graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected AndroidClipboard clipboard;
protected ApplicationListener listener;
public Handler handler;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected final SnapshotArray<LifecycleListener> lifecycleListeners = new SnapshotArray<LifecycleListener>(
LifecycleListener.class);
private final Array<AndroidEventListener> androidEventListeners = new Array<AndroidEventListener>();
protected int logLevel = LOG_INFO;
protected ApplicationLogger applicationLogger;
protected Callbacks callbacks;
@Override
public void onAttach (Activity activity) {
if (activity instanceof Callbacks) {
this.callbacks = (Callbacks)activity;
} else if (getParentFragment() instanceof Callbacks) {
this.callbacks = (Callbacks)getParentFragment();
} else if (getTargetFragment() instanceof Callbacks) {
this.callbacks = (Callbacks)getTargetFragment();
} else {
throw new RuntimeException(
"Missing AndroidFragmentApplication.Callbacks. Please implement AndroidFragmentApplication.Callbacks on the parent activity, fragment or target fragment.");
}
super.onAttach(activity);
}
@Override
public void onDetach () {
super.onDetach();
this.callbacks = null;
}
protected FrameLayout.LayoutParams createLayoutParams () {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void createWakeLock (boolean use) {
if (use) {
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@TargetApi(19)
@Override
public void useImmersiveMode (boolean use) {
if (!use || getVersion() < Build.VERSION_CODES.KITKAT) return;
View view = this.graphics.getView();
int code = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
view.setSystemUiVisibility(code);
}
/** This method has to be called in the
* {@link Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)} method. It sets up all
* the things necessary to get input, render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
* <p/>
* Note: you have to return the returned view from the
* {@link Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)}!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
return initializeForView(listener, config);
}
/** This method has to be called in the
* {@link Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)} method. It sets up all
* the things necessary to get input, render via OpenGL and so on. You can configure other aspects of the application with the
* rest of the fields in the {@link AndroidApplicationConfiguration} instance.
* <p/>
* Note: you have to return the returned view from
* {@link Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)}
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.).
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) {
if (this.getVersion() < MINIMUM_SDK) {
throw new GdxRuntimeException("libGDX requires Android API Level " + MINIMUM_SDK + " or later.");
}
GdxNativesLoader.load();
setApplicationLogger(new AndroidApplicationLogger());
graphics = new AndroidGraphics(this, config,
config.resolutionStrategy == null ? new FillResolutionStrategy() : config.resolutionStrategy);
input = createInput(this, getActivity(), graphics.view, config);
audio = createAudio(getActivity(), config);
files = createFiles();
net = new AndroidNet(this, config);
this.listener = listener;
this.handler = new Handler();
this.clipboard = new AndroidClipboard(getActivity());
// Add a specialized audio lifecycle listener
addLifecycleListener(new LifecycleListener() {
@Override
public void resume () {
audio.resume();
}
@Override
public void pause () {
audio.pause();
}
@Override
public void dispose () {
audio.dispose();
}
});
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
createWakeLock(config.useWakelock);
useImmersiveMode(config.useImmersiveMode);
if (config.useImmersiveMode && getVersion() >= Build.VERSION_CODES.KITKAT) {
AndroidVisibilityListener vlistener = new AndroidVisibilityListener();
vlistener.createListener(this);
}
// detect an already connected bluetooth keyboardAvailable
if (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS) input.setKeyboardAvailable(true);
return graphics.getView();
}
@Override
public void onPause () {
boolean isContinuous = graphics.isContinuousRendering();
boolean isContinuousEnforced = AndroidGraphics.enforceContinuousRendering;
// from here we don't want non continuous rendering
AndroidGraphics.enforceContinuousRendering = true;
graphics.setContinuousRendering(true);
// calls to setContinuousRendering(false) from other thread (ex: GLThread)
// will be ignored at this point...
graphics.pause();
input.onPause();
// davebaol & mobidevelop:
// This fragment (or one of the parent) is currently being removed from its activity or the activity is in the process of
// finishing
if (isRemoving() || isAnyParentFragmentRemoving() || getActivity().isFinishing()) {
graphics.clearManagedCaches();
graphics.destroy();
}
AndroidGraphics.enforceContinuousRendering = isContinuousEnforced;
graphics.setContinuousRendering(isContinuous);
graphics.onPauseGLSurfaceView();
super.onPause();
}
@Override
public void onResume () {
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
input.onResume();
if (graphics != null) {
graphics.onResumeGLSurfaceView();
}
if (!firstResume) {
graphics.resume();
} else
firstResume = false;
super.onResume();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public AndroidInput getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
@Override
public int getVersion () {
return android.os.Build.VERSION.SDK_INT;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(getActivity().getSharedPreferences(name, Context.MODE_PRIVATE));
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
@Override
public void onConfigurationChanged (Configuration config) {
super.onConfigurationChanged(config);
boolean keyboardAvailable = false;
if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true;
input.setKeyboardAvailable(keyboardAvailable);
}
@Override
public void exit () {
handler.post(new Runnable() {
@Override
public void run () {
callbacks.exit();
}
});
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) {
Log.d(tag, message);
}
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) {
Log.d(tag, message, exception);
}
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) Log.i(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) Log.i(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) Log.e(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) Log.e(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
public Context getContext () {
return getActivity();
}
@Override
public Array<Runnable> getRunnables () {
return runnables;
}
@Override
public Array<Runnable> getExecutedRunnables () {
return executedRunnables;
}
@Override
public void runOnUiThread (Runnable runnable) {
getActivity().runOnUiThread(runnable);
}
@Override
public SnapshotArray<LifecycleListener> getLifecycleListeners () {
return lifecycleListeners;
}
@Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// forward events to our listeners if there are any installed
synchronized (androidEventListeners) {
for (int i = 0; i < androidEventListeners.size; i++) {
androidEventListeners.get(i).onActivityResult(requestCode, resultCode, data);
}
}
}
/** Adds an event listener for Android specific event such as onActivityResult(...). */
public void addAndroidEventListener (AndroidEventListener listener) {
synchronized (androidEventListeners) {
androidEventListeners.add(listener);
}
}
/** Removes an event listener for Android specific event such as onActivityResult(...). */
public void removeAndroidEventListener (AndroidEventListener listener) {
synchronized (androidEventListeners) {
androidEventListeners.removeValue(listener, true);
}
}
@Override
public Window getApplicationWindow () {
return this.getActivity().getWindow();
}
@Override
public Handler getHandler () {
return this.handler;
}
@Override
public AndroidAudio createAudio (Context context, AndroidApplicationConfiguration config) {
return new DefaultAndroidAudio(context, config);
}
@Override
public AndroidInput createInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
return new DefaultAndroidInput(this, getActivity(), graphics.view, config);
}
protected AndroidFiles createFiles () {
return new DefaultAndroidFiles(getResources().getAssets(), getActivity(), true);
}
@Override
public WindowManager getWindowManager () {
return (WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE);
}
/** Iterates over nested fragments hierarchy and returns true if one of the fragment is in the removal process
*
* @return true - one of the parent fragments is being removed */
private boolean isAnyParentFragmentRemoving () {
Fragment fragment = getParentFragment();
while (fragment != null) {
if (fragment.isRemoving()) return true;
fragment = fragment.getParentFragment();
}
return false;
}
}
|
package com.badlogic.gdx.backends.android;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Debug;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import androidx.fragment.app.Fragment;
import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.utils.*;
/** Implementation of the {@link AndroidApplicationBase} that is based on the {@link Fragment} class. This class is similar in use
* to the {@link AndroidApplication} class, which is based on an {@link Activity}.
*
* @author Bartol Karuza ([email protected]) */
public class AndroidFragmentApplication extends Fragment implements AndroidApplicationBase {
/** Callbacks interface for letting the fragment interact with the Activitiy, parent fragment or target fragment.
*
* @author Bartol Karuza ([email protected]) */
public interface Callbacks {
void exit ();
}
protected AndroidGraphics graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected AndroidClipboard clipboard;
protected ApplicationListener listener;
public Handler handler;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected final SnapshotArray<LifecycleListener> lifecycleListeners = new SnapshotArray<LifecycleListener>(
LifecycleListener.class);
private final Array<AndroidEventListener> androidEventListeners = new Array<AndroidEventListener>();
protected int logLevel = LOG_INFO;
protected ApplicationLogger applicationLogger;
protected Callbacks callbacks;
@Override
public void onAttach (Activity activity) {
if (activity instanceof Callbacks) {
this.callbacks = (Callbacks)activity;
} else if (getParentFragment() instanceof Callbacks) {
this.callbacks = (Callbacks)getParentFragment();
} else if (getTargetFragment() instanceof Callbacks) {
this.callbacks = (Callbacks)getTargetFragment();
} else {
throw new RuntimeException(
"Missing AndroidFragmentApplication.Callbacks. Please implement AndroidFragmentApplication.Callbacks on the parent activity, fragment or target fragment.");
}
super.onAttach(activity);
}
@Override
public void onDetach () {
super.onDetach();
this.callbacks = null;
}
protected FrameLayout.LayoutParams createLayoutParams () {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.CENTER;
return layoutParams;
}
protected void createWakeLock (boolean use) {
if (use) {
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@TargetApi(19)
@Override
public void useImmersiveMode (boolean use) {
if (!use || getVersion() < Build.VERSION_CODES.KITKAT) return;
View view = this.graphics.getView();
int code = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
view.setSystemUiVisibility(code);
}
/** This method has to be called in the
* {@link Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)} method. It sets up all
* the things necessary to get input, render via OpenGL and so on. Uses a default {@link AndroidApplicationConfiguration}.
* <p/>
* Note: you have to return the returned view from the
* {@link Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)}!
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener) {
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
return initializeForView(listener, config);
}
/** This method has to be called in the
* {@link Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)} method. It sets up all
* the things necessary to get input, render via OpenGL and so on. You can configure other aspects of the application with the
* rest of the fields in the {@link AndroidApplicationConfiguration} instance.
* <p/>
* Note: you have to return the returned view from
* {@link Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)}
*
* @param listener the {@link ApplicationListener} implementing the program logic
* @param config the {@link AndroidApplicationConfiguration}, defining various settings of the application (use accelerometer,
* etc.).
* @return the GLSurfaceView of the application */
public View initializeForView (ApplicationListener listener, AndroidApplicationConfiguration config) {
if (this.getVersion() < MINIMUM_SDK) {
throw new GdxRuntimeException("libGDX requires Android API Level " + MINIMUM_SDK + " or later.");
}
GdxNativesLoader.load();
setApplicationLogger(new AndroidApplicationLogger());
graphics = new AndroidGraphics(this, config,
config.resolutionStrategy == null ? new FillResolutionStrategy() : config.resolutionStrategy);
input = createInput(this, getActivity(), graphics.view, config);
audio = createAudio(getActivity(), config);
files = createFiles();
net = new AndroidNet(this, config);
this.listener = listener;
this.handler = new Handler();
this.clipboard = new AndroidClipboard(getActivity());
// Add a specialized audio lifecycle listener
addLifecycleListener(new LifecycleListener() {
@Override
public void resume () {
audio.resume();
}
@Override
public void pause () {
audio.pause();
}
@Override
public void dispose () {
audio.dispose();
}
});
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
createWakeLock(config.useWakelock);
useImmersiveMode(config.useImmersiveMode);
if (config.useImmersiveMode && getVersion() >= Build.VERSION_CODES.KITKAT) {
AndroidVisibilityListener vlistener = new AndroidVisibilityListener();
vlistener.createListener(this);
}
// detect an already connected bluetooth keyboardAvailable
if (getResources().getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS) input.setKeyboardAvailable(true);
return graphics.getView();
}
@Override
public void onPause () {
boolean isContinuous = graphics.isContinuousRendering();
boolean isContinuousEnforced = AndroidGraphics.enforceContinuousRendering;
// from here we don't want non continuous rendering
AndroidGraphics.enforceContinuousRendering = true;
graphics.setContinuousRendering(true);
// calls to setContinuousRendering(false) from other thread (ex: GLThread)
// will be ignored at this point...
graphics.pause();
input.onPause();
// davebaol & mobidevelop:
// This fragment (or one of the parent) is currently being removed from its activity or the activity is in the process of
// finishing
if (isRemoving() || isAnyParentFragmentRemoving() || getActivity().isFinishing()) {
graphics.clearManagedCaches();
graphics.destroy();
}
AndroidGraphics.enforceContinuousRendering = isContinuousEnforced;
graphics.setContinuousRendering(isContinuous);
graphics.onPauseGLSurfaceView();
super.onPause();
}
@Override
public void onResume () {
Gdx.app = this;
Gdx.input = this.getInput();
Gdx.audio = this.getAudio();
Gdx.files = this.getFiles();
Gdx.graphics = this.getGraphics();
Gdx.net = this.getNet();
input.onResume();
if (graphics != null) {
graphics.onResumeGLSurfaceView();
}
if (!firstResume) {
graphics.resume();
} else
firstResume = false;
super.onResume();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public AndroidInput getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
@Override
public int getVersion () {
return android.os.Build.VERSION.SDK_INT;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(getActivity().getSharedPreferences(name, Context.MODE_PRIVATE));
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
@Override
public void onConfigurationChanged (Configuration config) {
super.onConfigurationChanged(config);
boolean keyboardAvailable = false;
if (config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) keyboardAvailable = true;
input.setKeyboardAvailable(keyboardAvailable);
}
@Override
public void exit () {
handler.post(new Runnable() {
@Override
public void run () {
callbacks.exit();
}
});
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) {
Log.d(tag, message);
}
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) {
Log.d(tag, message, exception);
}
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) Log.i(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) Log.i(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) Log.e(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) Log.e(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
public Context getContext () {
return getActivity();
}
@Override
public Array<Runnable> getRunnables () {
return runnables;
}
@Override
public Array<Runnable> getExecutedRunnables () {
return executedRunnables;
}
@Override
public void runOnUiThread (Runnable runnable) {
getActivity().runOnUiThread(runnable);
}
@Override
public SnapshotArray<LifecycleListener> getLifecycleListeners () {
return lifecycleListeners;
}
@Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// forward events to our listeners if there are any installed
synchronized (androidEventListeners) {
for (int i = 0; i < androidEventListeners.size; i++) {
androidEventListeners.get(i).onActivityResult(requestCode, resultCode, data);
}
}
}
/** Adds an event listener for Android specific event such as onActivityResult(...). */
public void addAndroidEventListener (AndroidEventListener listener) {
synchronized (androidEventListeners) {
androidEventListeners.add(listener);
}
}
/** Removes an event listener for Android specific event such as onActivityResult(...). */
public void removeAndroidEventListener (AndroidEventListener listener) {
synchronized (androidEventListeners) {
androidEventListeners.removeValue(listener, true);
}
}
@Override
public Window getApplicationWindow () {
return this.getActivity().getWindow();
}
@Override
public Handler getHandler () {
return this.handler;
}
@Override
public AndroidAudio createAudio (Context context, AndroidApplicationConfiguration config) {
if (!config.disableAudio)
return new DefaultAndroidAudio(context, config);
else
return new DisabledAndroidAudio();
}
@Override
public AndroidInput createInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
return new DefaultAndroidInput(this, getActivity(), graphics.view, config);
}
protected AndroidFiles createFiles () {
return new DefaultAndroidFiles(getResources().getAssets(), getActivity(), true);
}
@Override
public WindowManager getWindowManager () {
return (WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE);
}
/** Iterates over nested fragments hierarchy and returns true if one of the fragment is in the removal process
*
* @return true - one of the parent fragments is being removed */
private boolean isAnyParentFragmentRemoving () {
Fragment fragment = getParentFragment();
while (fragment != null) {
if (fragment.isRemoving()) return true;
fragment = fragment.getParentFragment();
}
return false;
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidLiveWallpaper.java | /*
* Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
*
* Modified by Elijah Cornell
* 2013.01 Modified by Jaroslaw Wisniewski <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.badlogic.gdx.backends.android;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Debug;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.utils.*;
/** An implementation of the {@link Application} interface to be used with an AndroidLiveWallpaperService. Not directly
* constructable, instead the {@link AndroidLiveWallpaperService} will create this class internally.
*
* @author mzechner */
public class AndroidLiveWallpaper implements AndroidApplicationBase {
protected AndroidLiveWallpaperService service;
protected AndroidGraphicsLiveWallpaper graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected AndroidClipboard clipboard;
protected ApplicationListener listener;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected final SnapshotArray<LifecycleListener> lifecycleListeners = new SnapshotArray<LifecycleListener>(
LifecycleListener.class);
protected int logLevel = LOG_INFO;
protected ApplicationLogger applicationLogger;
protected volatile Color[] wallpaperColors = null;
public AndroidLiveWallpaper (AndroidLiveWallpaperService service) {
this.service = service;
}
public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) {
if (this.getVersion() < MINIMUM_SDK) {
throw new GdxRuntimeException("libGDX requires Android API Level " + MINIMUM_SDK + " or later.");
}
GdxNativesLoader.load();
setApplicationLogger(new AndroidApplicationLogger());
graphics = new AndroidGraphicsLiveWallpaper(this, config,
config.resolutionStrategy == null ? new FillResolutionStrategy() : config.resolutionStrategy);
// factory in use, but note: AndroidInputFactory causes exceptions when obfuscated: java.lang.RuntimeException: Couldn't
// construct AndroidInput, this should never happen, proguard deletes constructor used only by reflection
input = createInput(this, this.getService(), graphics.view, config);
// input = new AndroidInput(this, this.getService(), null, config);
audio = createAudio(this.getService(), config);
files = createFiles();
net = new AndroidNet(this, config);
this.listener = listener;
clipboard = new AndroidClipboard(this.getService());
// Unlike activity, fragment and daydream applications there's no need for a specialized audio listener.
// See description in onPause method.
Gdx.app = this;
Gdx.input = input;
Gdx.audio = audio;
Gdx.files = files;
Gdx.graphics = graphics;
Gdx.net = net;
}
public void onPause () {
if (AndroidLiveWallpaperService.DEBUG) Log.d(AndroidLiveWallpaperService.TAG, " > AndroidLiveWallpaper - onPause()");
// IMPORTANT!
// jw: graphics.pause is never called, graphics.pause works on most devices but not on all..
// for example on Samsung Galaxy Tab (GT-P6800) on android 4.0.4 invoking graphics.pause causes "Fatal Signal 11"
// near mEglHelper.swap() in GLSurfaceView while processing next onPause event.
// See related issue:
// http://code.google.com/p/libgdx/issues/detail?id=541
// the problem with graphics.pause occurs while using OpenGL 2.0 and original GLSurfaceView while rotating device
// in lwp preview
// in my opinion it is a bug of android not libgdx, even example Cubic live wallpaper from
// Android SDK crashes on affected devices.......... and on some configurations of android emulator too.
//
// My wallpaper was rejected on Samsung Apps because of this issue, so I decided to disable graphics.pause..
// also I moved audio lifecycle methods from AndroidGraphicsLiveWallpaper into this class
// graphics.pause();
// if (AndroidLiveWallpaperService.DEBUG)
// Log.d(AndroidLiveWallpaperService.TAG, " > AndroidLiveWallpaper - onPause() application paused!");
audio.pause();
input.onPause();
if (graphics != null) {
graphics.onPauseGLSurfaceView();
}
if (AndroidLiveWallpaperService.DEBUG) Log.d(AndroidLiveWallpaperService.TAG, " > AndroidLiveWallpaper - onPause() done!");
}
public void onResume () {
Gdx.app = this;
Gdx.input = input;
Gdx.audio = audio;
Gdx.files = files;
Gdx.graphics = graphics;
Gdx.net = net;
input.onResume();
if (graphics != null) {
graphics.onResumeGLSurfaceView();
}
if (!firstResume) {
audio.resume();
graphics.resume();
} else
firstResume = false;
}
public void onDestroy () {
// it is too late to call graphics.destroy - it needs live gl GLThread and gl context, otherwise it will cause of deadlock
// if (graphics != null) {
// graphics.clearManagedCaches();
// graphics.destroy();
// }
// so we do what we can..
if (graphics != null) {
// not necessary - already called in AndroidLiveWallpaperService.onDeepPauseApplication
// app.graphics.clearManagedCaches();
// kill the GLThread managed by GLSurfaceView
graphics.onDestroyGLSurfaceView();
}
if (audio != null) {
// dispose audio and free native resources, mandatory since graphics.pause is never called in live wallpaper
audio.dispose();
}
}
@Override
public WindowManager getWindowManager () {
return service.getWindowManager();
}
public AndroidLiveWallpaperService getService () {
return service;
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
}
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public AndroidInput getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
@Override
public int getVersion () {
return android.os.Build.VERSION.SDK_INT;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(service.getSharedPreferences(name, Context.MODE_PRIVATE));
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void exit () {
// no-op
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
public Context getContext () {
return service;
}
@Override
public Array<Runnable> getRunnables () {
return runnables;
}
@Override
public Array<Runnable> getExecutedRunnables () {
return executedRunnables;
}
@Override
public SnapshotArray<LifecycleListener> getLifecycleListeners () {
return lifecycleListeners;
}
@Override
public void startActivity (Intent intent) {
service.startActivity(intent);
}
@Override
public Window getApplicationWindow () {
throw new UnsupportedOperationException();
}
@Override
public Handler getHandler () {
throw new UnsupportedOperationException();
}
@Override
public AndroidAudio createAudio (Context context, AndroidApplicationConfiguration config) {
return new DefaultAndroidAudio(context, config);
}
@Override
public AndroidInput createInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
return new DefaultAndroidInput(this, this.getService(), graphics.view, config);
}
protected AndroidFiles createFiles () {
// added initialization of android local storage: /data/data/<app package>/files/
this.getService().getFilesDir(); // workaround for Android bug #10515463
return new DefaultAndroidFiles(this.getService().getAssets(), this.getService(), true);
}
@Override
public void runOnUiThread (Runnable runnable) {
if (Looper.myLooper() != Looper.getMainLooper()) {
// The current thread is not the UI thread.
// Let's post the runnable to the event queue of the UI thread.
new Handler(Looper.getMainLooper()).post(runnable);
} else {
// The current thread is the UI thread already.
// Let's execute the runnable immediately.
runnable.run();
}
}
@Override
public void useImmersiveMode (boolean b) {
throw new UnsupportedOperationException();
}
/** Notify the wallpaper engine that the significant colors of the wallpaper have changed. This method may be called before
* initializing the live wallpaper.
* @param primaryColor The most visually significant color.
* @param secondaryColor The second most visually significant color.
* @param tertiaryColor The third most visually significant color. */
public void notifyColorsChanged (Color primaryColor, Color secondaryColor, Color tertiaryColor) {
if (Build.VERSION.SDK_INT < 27) return;
final Color[] colors = new Color[3];
colors[0] = new Color(primaryColor);
colors[1] = new Color(secondaryColor);
colors[2] = new Color(tertiaryColor);
wallpaperColors = colors;
AndroidLiveWallpaperService.AndroidWallpaperEngine engine = service.linkedEngine;
if (engine != null) engine.notifyColorsChanged();
}
}
| /*
* Copyright 2010 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
*
* Modified by Elijah Cornell
* 2013.01 Modified by Jaroslaw Wisniewski <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.badlogic.gdx.backends.android;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Debug;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import com.badlogic.gdx.*;
import com.badlogic.gdx.backends.android.surfaceview.FillResolutionStrategy;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.utils.*;
/** An implementation of the {@link Application} interface to be used with an AndroidLiveWallpaperService. Not directly
* constructable, instead the {@link AndroidLiveWallpaperService} will create this class internally.
*
* @author mzechner */
public class AndroidLiveWallpaper implements AndroidApplicationBase {
protected AndroidLiveWallpaperService service;
protected AndroidGraphicsLiveWallpaper graphics;
protected AndroidInput input;
protected AndroidAudio audio;
protected AndroidFiles files;
protected AndroidNet net;
protected AndroidClipboard clipboard;
protected ApplicationListener listener;
protected boolean firstResume = true;
protected final Array<Runnable> runnables = new Array<Runnable>();
protected final Array<Runnable> executedRunnables = new Array<Runnable>();
protected final SnapshotArray<LifecycleListener> lifecycleListeners = new SnapshotArray<LifecycleListener>(
LifecycleListener.class);
protected int logLevel = LOG_INFO;
protected ApplicationLogger applicationLogger;
protected volatile Color[] wallpaperColors = null;
public AndroidLiveWallpaper (AndroidLiveWallpaperService service) {
this.service = service;
}
public void initialize (ApplicationListener listener, AndroidApplicationConfiguration config) {
if (this.getVersion() < MINIMUM_SDK) {
throw new GdxRuntimeException("libGDX requires Android API Level " + MINIMUM_SDK + " or later.");
}
GdxNativesLoader.load();
setApplicationLogger(new AndroidApplicationLogger());
graphics = new AndroidGraphicsLiveWallpaper(this, config,
config.resolutionStrategy == null ? new FillResolutionStrategy() : config.resolutionStrategy);
// factory in use, but note: AndroidInputFactory causes exceptions when obfuscated: java.lang.RuntimeException: Couldn't
// construct AndroidInput, this should never happen, proguard deletes constructor used only by reflection
input = createInput(this, this.getService(), graphics.view, config);
// input = new AndroidInput(this, this.getService(), null, config);
audio = createAudio(this.getService(), config);
files = createFiles();
net = new AndroidNet(this, config);
this.listener = listener;
clipboard = new AndroidClipboard(this.getService());
// Unlike activity, fragment and daydream applications there's no need for a specialized audio listener.
// See description in onPause method.
Gdx.app = this;
Gdx.input = input;
Gdx.audio = audio;
Gdx.files = files;
Gdx.graphics = graphics;
Gdx.net = net;
}
public void onPause () {
if (AndroidLiveWallpaperService.DEBUG) Log.d(AndroidLiveWallpaperService.TAG, " > AndroidLiveWallpaper - onPause()");
// IMPORTANT!
// jw: graphics.pause is never called, graphics.pause works on most devices but not on all..
// for example on Samsung Galaxy Tab (GT-P6800) on android 4.0.4 invoking graphics.pause causes "Fatal Signal 11"
// near mEglHelper.swap() in GLSurfaceView while processing next onPause event.
// See related issue:
// http://code.google.com/p/libgdx/issues/detail?id=541
// the problem with graphics.pause occurs while using OpenGL 2.0 and original GLSurfaceView while rotating device
// in lwp preview
// in my opinion it is a bug of android not libgdx, even example Cubic live wallpaper from
// Android SDK crashes on affected devices.......... and on some configurations of android emulator too.
//
// My wallpaper was rejected on Samsung Apps because of this issue, so I decided to disable graphics.pause..
// also I moved audio lifecycle methods from AndroidGraphicsLiveWallpaper into this class
// graphics.pause();
// if (AndroidLiveWallpaperService.DEBUG)
// Log.d(AndroidLiveWallpaperService.TAG, " > AndroidLiveWallpaper - onPause() application paused!");
audio.pause();
input.onPause();
if (graphics != null) {
graphics.onPauseGLSurfaceView();
}
if (AndroidLiveWallpaperService.DEBUG) Log.d(AndroidLiveWallpaperService.TAG, " > AndroidLiveWallpaper - onPause() done!");
}
public void onResume () {
Gdx.app = this;
Gdx.input = input;
Gdx.audio = audio;
Gdx.files = files;
Gdx.graphics = graphics;
Gdx.net = net;
input.onResume();
if (graphics != null) {
graphics.onResumeGLSurfaceView();
}
if (!firstResume) {
audio.resume();
graphics.resume();
} else
firstResume = false;
}
public void onDestroy () {
// it is too late to call graphics.destroy - it needs live gl GLThread and gl context, otherwise it will cause of deadlock
// if (graphics != null) {
// graphics.clearManagedCaches();
// graphics.destroy();
// }
// so we do what we can..
if (graphics != null) {
// not necessary - already called in AndroidLiveWallpaperService.onDeepPauseApplication
// app.graphics.clearManagedCaches();
// kill the GLThread managed by GLSurfaceView
graphics.onDestroyGLSurfaceView();
}
if (audio != null) {
// dispose audio and free native resources, mandatory since graphics.pause is never called in live wallpaper
audio.dispose();
}
}
@Override
public WindowManager getWindowManager () {
return service.getWindowManager();
}
public AndroidLiveWallpaperService getService () {
return service;
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
}
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public AndroidInput getInput () {
return input;
}
@Override
public Net getNet () {
return net;
}
@Override
public ApplicationType getType () {
return ApplicationType.Android;
}
@Override
public int getVersion () {
return android.os.Build.VERSION.SDK_INT;
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return Debug.getNativeHeapAllocatedSize();
}
@Override
public Preferences getPreferences (String name) {
return new AndroidPreferences(service.getSharedPreferences(name, Context.MODE_PRIVATE));
}
@Override
public Clipboard getClipboard () {
return clipboard;
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public void exit () {
// no-op
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
@Override
public Context getContext () {
return service;
}
@Override
public Array<Runnable> getRunnables () {
return runnables;
}
@Override
public Array<Runnable> getExecutedRunnables () {
return executedRunnables;
}
@Override
public SnapshotArray<LifecycleListener> getLifecycleListeners () {
return lifecycleListeners;
}
@Override
public void startActivity (Intent intent) {
service.startActivity(intent);
}
@Override
public Window getApplicationWindow () {
throw new UnsupportedOperationException();
}
@Override
public Handler getHandler () {
throw new UnsupportedOperationException();
}
@Override
public AndroidAudio createAudio (Context context, AndroidApplicationConfiguration config) {
if (!config.disableAudio)
return new DefaultAndroidAudio(context, config);
else
return new DisabledAndroidAudio();
}
@Override
public AndroidInput createInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
return new DefaultAndroidInput(this, this.getService(), graphics.view, config);
}
protected AndroidFiles createFiles () {
// added initialization of android local storage: /data/data/<app package>/files/
this.getService().getFilesDir(); // workaround for Android bug #10515463
return new DefaultAndroidFiles(this.getService().getAssets(), this.getService(), true);
}
@Override
public void runOnUiThread (Runnable runnable) {
if (Looper.myLooper() != Looper.getMainLooper()) {
// The current thread is not the UI thread.
// Let's post the runnable to the event queue of the UI thread.
new Handler(Looper.getMainLooper()).post(runnable);
} else {
// The current thread is the UI thread already.
// Let's execute the runnable immediately.
runnable.run();
}
}
@Override
public void useImmersiveMode (boolean b) {
throw new UnsupportedOperationException();
}
/** Notify the wallpaper engine that the significant colors of the wallpaper have changed. This method may be called before
* initializing the live wallpaper.
* @param primaryColor The most visually significant color.
* @param secondaryColor The second most visually significant color.
* @param tertiaryColor The third most visually significant color. */
public void notifyColorsChanged (Color primaryColor, Color secondaryColor, Color tertiaryColor) {
if (Build.VERSION.SDK_INT < 27) return;
final Color[] colors = new Color[3];
colors[0] = new Color(primaryColor);
colors[1] = new Color(secondaryColor);
colors[2] = new Color(tertiaryColor);
wallpaperColors = colors;
AndroidLiveWallpaperService.AndroidWallpaperEngine engine = service.linkedEngine;
if (engine != null) engine.notifyColorsChanged();
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AsynchronousAndroidAudio.java |
package com.badlogic.gdx.backends.android;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
/** A performance oriented implementation of the {@link AndroidAudio} interface.
*
* Sounds are played on a separate thread. This avoids waiting for sound ids on methods that can potentially lock main thread for
* considerable amount of time, especially when playing several sounds at the same time. The limitation of this approach is that
* methods that require a sound id are not supported. */
public class AsynchronousAndroidAudio extends DefaultAndroidAudio {
private final HandlerThread handlerThread;
private final Handler handler;
public AsynchronousAndroidAudio (Context context, AndroidApplicationConfiguration config) {
super(context, config);
if (!config.disableAudio) {
handlerThread = new HandlerThread("libGDX Sound Management");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
} else {
handler = null;
handlerThread = null;
}
}
@Override
public void dispose () {
super.dispose();
if (handlerThread != null) {
handlerThread.quit();
}
}
@Override
public Sound newSound (FileHandle file) {
Sound sound = super.newSound(file);
return new AsynchronousSound(sound, handler);
}
}
|
package com.badlogic.gdx.backends.android;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
/** A performance oriented implementation of the {@link AndroidAudio} interface.
*
* Sounds are played on a separate thread. This avoids waiting for sound ids on methods that can potentially lock main thread for
* considerable amount of time, especially when playing several sounds at the same time. The limitation of this approach is that
* methods that require a sound id are not supported. */
public class AsynchronousAndroidAudio extends DefaultAndroidAudio {
private final HandlerThread handlerThread;
private final Handler handler;
public AsynchronousAndroidAudio (Context context, AndroidApplicationConfiguration config) {
super(context, config);
handlerThread = new HandlerThread("libGDX Sound Management");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
@Override
public void dispose () {
super.dispose();
if (handlerThread != null) {
handlerThread.quit();
}
}
@Override
public Sound newSound (FileHandle file) {
Sound sound = super.newSound(file);
return new AsynchronousSound(sound, handler);
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/DefaultAndroidAudio.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/** An implementation of the {@link Audio} interface for Android.
*
* @author mzechner */
public class DefaultAndroidAudio implements AndroidAudio {
private final SoundPool soundPool;
private final AudioManager manager;
private final List<AndroidMusic> musics = new ArrayList<AndroidMusic>();
public DefaultAndroidAudio (Context context, AndroidApplicationConfiguration config) {
if (!config.disableAudio) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes audioAttrib = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build();
soundPool = new SoundPool.Builder().setAudioAttributes(audioAttrib).setMaxStreams(config.maxSimultaneousSounds)
.build();
} else {
soundPool = new SoundPool(config.maxSimultaneousSounds, AudioManager.STREAM_MUSIC, 0);// srcQuality: the sample-rate
// converter quality. Currently
// has no effect. Use 0 for the
// default.
}
manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
if (context instanceof Activity) {
((Activity)context).setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
} else {
soundPool = null;
manager = null;
}
}
@Override
public void pause () {
if (soundPool == null) {
return;
}
synchronized (musics) {
for (AndroidMusic music : musics) {
if (music.isPlaying()) {
music.pause();
music.wasPlaying = true;
} else
music.wasPlaying = false;
}
}
this.soundPool.autoPause();
}
@Override
public void resume () {
if (soundPool == null) {
return;
}
synchronized (musics) {
for (int i = 0; i < musics.size(); i++) {
if (musics.get(i).wasPlaying) musics.get(i).play();
}
}
this.soundPool.autoResume();
}
/** {@inheritDoc} */
@Override
public AudioDevice newAudioDevice (int samplingRate, boolean isMono) {
if (soundPool == null) {
throw new GdxRuntimeException("Android audio is not enabled by the application config.");
}
return new AndroidAudioDevice(samplingRate, isMono);
}
/** {@inheritDoc} */
@Override
public Music newMusic (FileHandle file) {
if (soundPool == null) {
throw new GdxRuntimeException("Android audio is not enabled by the application config.");
}
AndroidFileHandle aHandle = (AndroidFileHandle)file;
MediaPlayer mediaPlayer = createMediaPlayer();
if (aHandle.type() == FileType.Internal) {
try {
AssetFileDescriptor descriptor = aHandle.getAssetFileDescriptor();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mediaPlayer.prepare();
AndroidMusic music = new AndroidMusic(this, mediaPlayer);
synchronized (musics) {
musics.add(music);
}
return music;
} catch (Exception ex) {
throw new GdxRuntimeException(
"Error loading audio file: " + file + "\nNote: Internal audio files must be placed in the assets directory.", ex);
}
} else {
try {
mediaPlayer.setDataSource(aHandle.file().getPath());
mediaPlayer.prepare();
AndroidMusic music = new AndroidMusic(this, mediaPlayer);
synchronized (musics) {
musics.add(music);
}
return music;
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading audio file: " + file, ex);
}
}
}
@Override
public boolean switchOutputDevice (String deviceIdentifier) {
return true;
}
@Override
public String[] getAvailableOutputDevices () {
return new String[0];
}
/** Creates a new Music instance from the provided FileDescriptor. It is the caller's responsibility to close the file
* descriptor. It is safe to do so as soon as this call returns.
*
* @param fd the FileDescriptor from which to create the Music
*
* @see Audio#newMusic(FileHandle) */
public Music newMusic (FileDescriptor fd) {
if (soundPool == null) {
throw new GdxRuntimeException("Android audio is not enabled by the application config.");
}
MediaPlayer mediaPlayer = createMediaPlayer();
try {
mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
AndroidMusic music = new AndroidMusic(this, mediaPlayer);
synchronized (musics) {
musics.add(music);
}
return music;
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading audio from FileDescriptor", ex);
}
}
/** {@inheritDoc} */
@Override
public Sound newSound (FileHandle file) {
if (soundPool == null) {
throw new GdxRuntimeException("Android audio is not enabled by the application config.");
}
AndroidSound androidSound;
AndroidFileHandle aHandle = (AndroidFileHandle)file;
if (aHandle.type() == FileType.Internal) {
try {
AssetFileDescriptor descriptor = aHandle.getAssetFileDescriptor();
androidSound = new AndroidSound(soundPool, manager, soundPool.load(descriptor, 1));
descriptor.close();
} catch (IOException ex) {
throw new GdxRuntimeException(
"Error loading audio file: " + file + "\nNote: Internal audio files must be placed in the assets directory.", ex);
}
} else {
try {
androidSound = new AndroidSound(soundPool, manager, soundPool.load(aHandle.file().getPath(), 1));
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading audio file: " + file, ex);
}
}
return androidSound;
}
/** {@inheritDoc} */
@Override
public AudioRecorder newAudioRecorder (int samplingRate, boolean isMono) {
if (soundPool == null) {
throw new GdxRuntimeException("Android audio is not enabled by the application config.");
}
return new AndroidAudioRecorder(samplingRate, isMono);
}
/** Kills the soundpool and all other resources */
@Override
public void dispose () {
if (soundPool == null) {
return;
}
synchronized (musics) {
// gah i hate myself.... music.dispose() removes the music from the list...
ArrayList<AndroidMusic> musicsCopy = new ArrayList<AndroidMusic>(musics);
for (AndroidMusic music : musicsCopy) {
music.dispose();
}
}
soundPool.release();
}
@Override
public void notifyMusicDisposed (AndroidMusic music) {
synchronized (musics) {
musics.remove(this);
}
}
protected MediaPlayer createMediaPlayer () {
MediaPlayer mediaPlayer = new MediaPlayer();
if (Build.VERSION.SDK_INT <= 21) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} else {
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_GAME).build());
}
return mediaPlayer;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.android;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/** An implementation of the {@link Audio} interface for Android.
*
* @author mzechner */
public class DefaultAndroidAudio implements AndroidAudio {
private final SoundPool soundPool;
private final AudioManager manager;
private final List<AndroidMusic> musics = new ArrayList<AndroidMusic>();
public DefaultAndroidAudio (Context context, AndroidApplicationConfiguration config) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes audioAttrib = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build();
soundPool = new SoundPool.Builder().setAudioAttributes(audioAttrib).setMaxStreams(config.maxSimultaneousSounds).build();
} else {
soundPool = new SoundPool(config.maxSimultaneousSounds, AudioManager.STREAM_MUSIC, 0);// srcQuality: the sample-rate
// converter quality. Currently
// has no effect. Use 0 for the
// default.
}
manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
if (context instanceof Activity) {
((Activity)context).setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
}
@Override
public void pause () {
synchronized (musics) {
for (AndroidMusic music : musics) {
if (music.isPlaying()) {
music.pause();
music.wasPlaying = true;
} else
music.wasPlaying = false;
}
}
this.soundPool.autoPause();
}
@Override
public void resume () {
synchronized (musics) {
for (int i = 0; i < musics.size(); i++) {
if (musics.get(i).wasPlaying) musics.get(i).play();
}
}
this.soundPool.autoResume();
}
/** {@inheritDoc} */
@Override
public AudioDevice newAudioDevice (int samplingRate, boolean isMono) {
return new AndroidAudioDevice(samplingRate, isMono);
}
/** {@inheritDoc} */
@Override
public Music newMusic (FileHandle file) {
AndroidFileHandle aHandle = (AndroidFileHandle)file;
MediaPlayer mediaPlayer = createMediaPlayer();
if (aHandle.type() == FileType.Internal) {
try {
AssetFileDescriptor descriptor = aHandle.getAssetFileDescriptor();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mediaPlayer.prepare();
AndroidMusic music = new AndroidMusic(this, mediaPlayer);
synchronized (musics) {
musics.add(music);
}
return music;
} catch (Exception ex) {
throw new GdxRuntimeException(
"Error loading audio file: " + file + "\nNote: Internal audio files must be placed in the assets directory.", ex);
}
} else {
try {
mediaPlayer.setDataSource(aHandle.file().getPath());
mediaPlayer.prepare();
AndroidMusic music = new AndroidMusic(this, mediaPlayer);
synchronized (musics) {
musics.add(music);
}
return music;
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading audio file: " + file, ex);
}
}
}
@Override
public boolean switchOutputDevice (String deviceIdentifier) {
return true;
}
@Override
public String[] getAvailableOutputDevices () {
return new String[0];
}
/** Creates a new Music instance from the provided FileDescriptor. It is the caller's responsibility to close the file
* descriptor. It is safe to do so as soon as this call returns.
*
* @param fd the FileDescriptor from which to create the Music
*
* @see Audio#newMusic(FileHandle) */
public Music newMusic (FileDescriptor fd) {
MediaPlayer mediaPlayer = createMediaPlayer();
try {
mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
AndroidMusic music = new AndroidMusic(this, mediaPlayer);
synchronized (musics) {
musics.add(music);
}
return music;
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading audio from FileDescriptor", ex);
}
}
/** {@inheritDoc} */
@Override
public Sound newSound (FileHandle file) {
AndroidSound androidSound;
AndroidFileHandle aHandle = (AndroidFileHandle)file;
if (aHandle.type() == FileType.Internal) {
try {
AssetFileDescriptor descriptor = aHandle.getAssetFileDescriptor();
androidSound = new AndroidSound(soundPool, manager, soundPool.load(descriptor, 1));
descriptor.close();
} catch (IOException ex) {
throw new GdxRuntimeException(
"Error loading audio file: " + file + "\nNote: Internal audio files must be placed in the assets directory.", ex);
}
} else {
try {
androidSound = new AndroidSound(soundPool, manager, soundPool.load(aHandle.file().getPath(), 1));
} catch (Exception ex) {
throw new GdxRuntimeException("Error loading audio file: " + file, ex);
}
}
return androidSound;
}
/** {@inheritDoc} */
@Override
public AudioRecorder newAudioRecorder (int samplingRate, boolean isMono) {
return new AndroidAudioRecorder(samplingRate, isMono);
}
/** Kills the soundpool and all other resources */
@Override
public void dispose () {
synchronized (musics) {
// gah i hate myself.... music.dispose() removes the music from the list...
ArrayList<AndroidMusic> musicsCopy = new ArrayList<AndroidMusic>(musics);
for (AndroidMusic music : musicsCopy) {
music.dispose();
}
}
soundPool.release();
}
@Override
public void notifyMusicDisposed (AndroidMusic music) {
synchronized (musics) {
musics.remove(this);
}
}
protected MediaPlayer createMediaPlayer () {
MediaPlayer mediaPlayer = new MediaPlayer();
if (Build.VERSION.SDK_INT <= 21) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} else {
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_GAME).build());
}
return mediaPlayer;
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-robovm-metalangle/src/com/badlogic/gdx/backends/iosrobovm/IOSApplication.java | /*DO NOT EDIT THIS FILE - it is machine generated*/
package com.badlogic.gdx.backends.iosrobovm;
import java.io.File;
import com.badlogic.gdx.ApplicationLogger;
import com.badlogic.gdx.backends.iosrobovm.objectal.OALIOSAudio;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.foundation.NSMutableDictionary;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSProcessInfo;
import org.robovm.apple.foundation.NSString;
import org.robovm.apple.uikit.UIApplication;
import org.robovm.apple.uikit.UIApplicationDelegateAdapter;
import org.robovm.apple.uikit.UIApplicationLaunchOptions;
import org.robovm.apple.uikit.UIDevice;
import org.robovm.apple.uikit.UIUserInterfaceIdiom;
import org.robovm.apple.uikit.UIPasteboard;
import org.robovm.apple.uikit.UIScreen;
import org.robovm.apple.uikit.UIViewController;
import org.robovm.apple.uikit.UIWindow;
import org.robovm.rt.bro.Bro;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.LifecycleListener;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
/** DO NOT EDIT THIS FILE - it is machine generated */
public class IOSApplication implements Application {
/** DO NOT EDIT THIS FILE - it is machine generated */
public static abstract class Delegate extends UIApplicationDelegateAdapter {
private IOSApplication app;
protected abstract IOSApplication createApplication ();
@Override
public boolean didFinishLaunching (UIApplication application, UIApplicationLaunchOptions launchOptions) {
// Prevent this from being GCed until the ObjC UIApplication is deallocated
application.addStrongRef(this);
this.app = createApplication();
return app.didFinishLaunching(application, launchOptions);
}
@Override
public void didBecomeActive (UIApplication application) {
app.didBecomeActive(application);
}
@Override
public void willEnterForeground (UIApplication application) {
app.willEnterForeground(application);
}
@Override
public void willResignActive (UIApplication application) {
app.willResignActive(application);
}
@Override
public void willTerminate (UIApplication application) {
app.willTerminate(application);
}
}
static final boolean IS_METALANGLE = true;
UIApplication uiApp;
UIWindow uiWindow;
ApplicationListener listener;
IOSViewControllerListener viewControllerListener;
IOSApplicationConfiguration config;
IOSGraphics graphics;
IOSAudio audio;
Files files;
IOSInput input;
IOSNet net;
int logLevel = Application.LOG_DEBUG;
ApplicationLogger applicationLogger;
/** The display scale factor (1.0f for normal; 2.0f to use retina coordinates/dimensions). */
float pixelsPerPoint;
private IOSScreenBounds lastScreenBounds = null;
Array<Runnable> runnables = new Array<Runnable>();
Array<Runnable> executedRunnables = new Array<Runnable>();
Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
public IOSApplication (ApplicationListener listener, IOSApplicationConfiguration config) {
this.listener = listener;
this.config = config;
}
final boolean didFinishLaunching (UIApplication uiApp, UIApplicationLaunchOptions options) {
setApplicationLogger(new IOSApplicationLogger());
Gdx.app = this;
this.uiApp = uiApp;
// enable or disable screen dimming
uiApp.setIdleTimerDisabled(config.preventScreenDimming);
Gdx.app.debug("IOSApplication", "iOS version: " + UIDevice.getCurrentDevice().getSystemVersion());
Gdx.app.debug("IOSApplication", "Running in " + (Bro.IS_64BIT ? "64-bit" : "32-bit") + " mode");
// iOS counts in "points" instead of pixels. Points are logical pixels
pixelsPerPoint = (float)UIScreen.getMainScreen().getNativeScale();
Gdx.app.debug("IOSApplication", "Pixels per point: " + pixelsPerPoint);
this.uiWindow = new UIWindow(UIScreen.getMainScreen().getBounds());
this.uiWindow.makeKeyAndVisible();
uiApp.getDelegate().setWindow(uiWindow);
// setup libgdx
this.input = createInput();
this.graphics = createGraphics();
Gdx.gl = Gdx.gl20 = graphics.gl20;
Gdx.gl30 = graphics.gl30;
this.files = createFiles();
this.audio = createAudio(config);
this.net = new IOSNet(this, config);
Gdx.files = this.files;
Gdx.graphics = this.graphics;
Gdx.audio = this.audio;
Gdx.input = this.input;
Gdx.net = this.net;
this.input.setupPeripherals();
this.uiWindow.setRootViewController(this.graphics.viewController);
this.graphics.updateSafeInsets();
Gdx.app.debug("IOSApplication", "created");
listener.create();
listener.resize(this.graphics.getWidth(), this.graphics.getHeight());
// make sure the OpenGL view has contents before displaying it
this.graphics.view.display();
return true;
}
protected Files createFiles () {
return new IOSFiles();
}
protected IOSAudio createAudio (IOSApplicationConfiguration config) {
return new OALIOSAudio(config);
}
protected IOSGraphics createGraphics () {
return new IOSGraphics(this, config, input, config.useGL30);
}
protected IOSUIViewController createUIViewController (IOSGraphics graphics) {
return new IOSUIViewController(this, graphics);
}
protected IOSInput createInput () {
return new DefaultIOSInput(this);
}
/** Returns device ppi using a best guess approach when device is unknown. Overwrite to customize strategy. */
protected int guessUnknownPpi () {
int ppi;
if (UIDevice.getCurrentDevice().getUserInterfaceIdiom() == UIUserInterfaceIdiom.Pad)
ppi = 132 * (int)pixelsPerPoint;
else
ppi = 164 * (int)pixelsPerPoint;
error("IOSApplication", "Device PPI unknown. PPI value has been guessed to " + ppi + " but may be wrong");
return ppi;
}
/** Return the UI view controller of IOSApplication
* @return the view controller of IOSApplication */
public UIViewController getUIViewController () {
return graphics.viewController;
}
/** Return the UI Window of IOSApplication
* @return the window */
public UIWindow getUIWindow () {
return uiWindow;
}
/** @see IOSScreenBounds for detailed explanation
* @return logical dimensions of space we draw to, adjusted for device orientation */
protected IOSScreenBounds computeBounds () {
CGRect screenBounds = uiWindow.getBounds();
final CGRect statusBarFrame = uiApp.getStatusBarFrame();
double statusBarHeight = statusBarFrame.getHeight();
double screenWidth = screenBounds.getWidth();
double screenHeight = screenBounds.getHeight();
if (statusBarHeight != 0.0) {
debug("IOSApplication", "Status bar is visible (height = " + statusBarHeight + ")");
screenHeight -= statusBarHeight;
} else {
debug("IOSApplication", "Status bar is not visible");
}
final int offsetX = 0;
final int offsetY = (int)Math.round(statusBarHeight);
final int width = (int)Math.round(screenWidth);
final int height = (int)Math.round(screenHeight);
final int backBufferWidth = (int)Math.round(screenWidth * pixelsPerPoint);
final int backBufferHeight = (int)Math.round(screenHeight * pixelsPerPoint);
debug("IOSApplication", "Computed bounds are x=" + offsetX + " y=" + offsetY + " w=" + width + " h=" + height + " bbW= "
+ backBufferWidth + " bbH= " + backBufferHeight);
return lastScreenBounds = new IOSScreenBounds(offsetX, offsetY, width, height, backBufferWidth, backBufferHeight);
}
/** @return area of screen in UIKit points on which libGDX draws, with 0,0 being upper left corner */
public IOSScreenBounds getScreenBounds () {
if (lastScreenBounds == null)
return computeBounds();
else
return lastScreenBounds;
}
final void didBecomeActive (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "resumed");
audio.didBecomeActive();
graphics.makeCurrent();
graphics.resume();
}
final void willEnterForeground (UIApplication uiApp) {
audio.willEnterForeground();
}
final void willResignActive (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "paused");
audio.willResignActive();
graphics.makeCurrent();
graphics.pause();
Gdx.gl.glFinish();
}
final void willTerminate (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "disposed");
audio.willTerminate();
graphics.makeCurrent();
Array<LifecycleListener> listeners = lifecycleListeners;
synchronized (listeners) {
for (LifecycleListener listener : listeners) {
listener.pause();
}
}
listener.dispose();
Gdx.gl.glFinish();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Input getInput () {
return input;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Net getNet () {
return net;
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public ApplicationType getType () {
return ApplicationType.iOS;
}
@Override
public int getVersion () {
return (int)NSProcessInfo.getSharedProcessInfo().getOperatingSystemVersion().getMajorVersion();
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return getJavaHeap();
}
@Override
public Preferences getPreferences (String name) {
File libraryPath = new File(System.getenv("HOME"), "Library");
File finalPath = new File(libraryPath, name + ".plist");
@SuppressWarnings("unchecked")
NSMutableDictionary<NSString, NSObject> nsDictionary = (NSMutableDictionary<NSString, NSObject>)NSMutableDictionary
.read(finalPath);
// if it fails to get an existing dictionary, create a new one.
if (nsDictionary == null) {
nsDictionary = new NSMutableDictionary<NSString, NSObject>();
nsDictionary.write(finalPath, false);
}
return new IOSPreferences(nsDictionary, finalPath.getAbsolutePath());
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
public void processRunnables () {
synchronized (runnables) {
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
}
for (int i = 0; i < executedRunnables.size; i++) {
try {
executedRunnables.get(i).run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@Override
public void exit () {
System.exit(0);
}
@Override
public Clipboard getClipboard () {
return new Clipboard() {
@Override
public void setContents (String content) {
UIPasteboard.getGeneralPasteboard().setString(content);
}
@Override
public boolean hasContents () {
return UIPasteboard.getGeneralPasteboard().hasStrings();
}
@Override
public String getContents () {
return UIPasteboard.getGeneralPasteboard().getString();
}
};
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
/** Add a listener to handle events from the libGDX root view controller
* @param listener The {#link IOSViewControllerListener} to add */
public void addViewControllerListener (IOSViewControllerListener listener) {
viewControllerListener = listener;
}
}
| /*DO NOT EDIT THIS FILE - it is machine generated*/
package com.badlogic.gdx.backends.iosrobovm;
import java.io.File;
import com.badlogic.gdx.ApplicationLogger;
import com.badlogic.gdx.backends.iosrobovm.objectal.OALIOSAudio;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.foundation.NSMutableDictionary;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSProcessInfo;
import org.robovm.apple.foundation.NSString;
import org.robovm.apple.uikit.UIApplication;
import org.robovm.apple.uikit.UIApplicationDelegateAdapter;
import org.robovm.apple.uikit.UIApplicationLaunchOptions;
import org.robovm.apple.uikit.UIDevice;
import org.robovm.apple.uikit.UIUserInterfaceIdiom;
import org.robovm.apple.uikit.UIPasteboard;
import org.robovm.apple.uikit.UIScreen;
import org.robovm.apple.uikit.UIViewController;
import org.robovm.apple.uikit.UIWindow;
import org.robovm.rt.bro.Bro;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.LifecycleListener;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
/** DO NOT EDIT THIS FILE - it is machine generated */
public class IOSApplication implements Application {
/** DO NOT EDIT THIS FILE - it is machine generated */
public static abstract class Delegate extends UIApplicationDelegateAdapter {
private IOSApplication app;
protected abstract IOSApplication createApplication ();
@Override
public boolean didFinishLaunching (UIApplication application, UIApplicationLaunchOptions launchOptions) {
// Prevent this from being GCed until the ObjC UIApplication is deallocated
application.addStrongRef(this);
this.app = createApplication();
return app.didFinishLaunching(application, launchOptions);
}
@Override
public void didBecomeActive (UIApplication application) {
app.didBecomeActive(application);
}
@Override
public void willEnterForeground (UIApplication application) {
app.willEnterForeground(application);
}
@Override
public void willResignActive (UIApplication application) {
app.willResignActive(application);
}
@Override
public void willTerminate (UIApplication application) {
app.willTerminate(application);
}
}
static final boolean IS_METALANGLE = true;
UIApplication uiApp;
UIWindow uiWindow;
ApplicationListener listener;
IOSViewControllerListener viewControllerListener;
IOSApplicationConfiguration config;
IOSGraphics graphics;
IOSAudio audio;
Files files;
IOSInput input;
IOSNet net;
int logLevel = Application.LOG_DEBUG;
ApplicationLogger applicationLogger;
/** The display scale factor (1.0f for normal; 2.0f to use retina coordinates/dimensions). */
float pixelsPerPoint;
private IOSScreenBounds lastScreenBounds = null;
Array<Runnable> runnables = new Array<Runnable>();
Array<Runnable> executedRunnables = new Array<Runnable>();
Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
public IOSApplication (ApplicationListener listener, IOSApplicationConfiguration config) {
this.listener = listener;
this.config = config;
}
final boolean didFinishLaunching (UIApplication uiApp, UIApplicationLaunchOptions options) {
setApplicationLogger(new IOSApplicationLogger());
Gdx.app = this;
this.uiApp = uiApp;
// enable or disable screen dimming
uiApp.setIdleTimerDisabled(config.preventScreenDimming);
Gdx.app.debug("IOSApplication", "iOS version: " + UIDevice.getCurrentDevice().getSystemVersion());
Gdx.app.debug("IOSApplication", "Running in " + (Bro.IS_64BIT ? "64-bit" : "32-bit") + " mode");
// iOS counts in "points" instead of pixels. Points are logical pixels
pixelsPerPoint = (float)UIScreen.getMainScreen().getNativeScale();
Gdx.app.debug("IOSApplication", "Pixels per point: " + pixelsPerPoint);
this.uiWindow = new UIWindow(UIScreen.getMainScreen().getBounds());
this.uiWindow.makeKeyAndVisible();
uiApp.getDelegate().setWindow(uiWindow);
// setup libgdx
this.input = createInput();
this.graphics = createGraphics();
Gdx.gl = Gdx.gl20 = graphics.gl20;
Gdx.gl30 = graphics.gl30;
this.files = createFiles();
this.audio = createAudio(config);
this.net = new IOSNet(this, config);
Gdx.files = this.files;
Gdx.graphics = this.graphics;
Gdx.audio = this.audio;
Gdx.input = this.input;
Gdx.net = this.net;
this.input.setupPeripherals();
this.uiWindow.setRootViewController(this.graphics.viewController);
this.graphics.updateSafeInsets();
Gdx.app.debug("IOSApplication", "created");
listener.create();
listener.resize(this.graphics.getWidth(), this.graphics.getHeight());
// make sure the OpenGL view has contents before displaying it
this.graphics.view.display();
return true;
}
protected Files createFiles () {
return new IOSFiles();
}
protected IOSAudio createAudio (IOSApplicationConfiguration config) {
if (config.useAudio)
return new OALIOSAudio(config);
else
return new DisabledIOSAudio();
}
protected IOSGraphics createGraphics () {
return new IOSGraphics(this, config, input, config.useGL30);
}
protected IOSUIViewController createUIViewController (IOSGraphics graphics) {
return new IOSUIViewController(this, graphics);
}
protected IOSInput createInput () {
return new DefaultIOSInput(this);
}
/** Returns device ppi using a best guess approach when device is unknown. Overwrite to customize strategy. */
protected int guessUnknownPpi () {
int ppi;
if (UIDevice.getCurrentDevice().getUserInterfaceIdiom() == UIUserInterfaceIdiom.Pad)
ppi = 132 * (int)pixelsPerPoint;
else
ppi = 164 * (int)pixelsPerPoint;
error("IOSApplication", "Device PPI unknown. PPI value has been guessed to " + ppi + " but may be wrong");
return ppi;
}
/** Return the UI view controller of IOSApplication
* @return the view controller of IOSApplication */
public UIViewController getUIViewController () {
return graphics.viewController;
}
/** Return the UI Window of IOSApplication
* @return the window */
public UIWindow getUIWindow () {
return uiWindow;
}
/** @see IOSScreenBounds for detailed explanation
* @return logical dimensions of space we draw to, adjusted for device orientation */
protected IOSScreenBounds computeBounds () {
CGRect screenBounds = uiWindow.getBounds();
final CGRect statusBarFrame = uiApp.getStatusBarFrame();
double statusBarHeight = statusBarFrame.getHeight();
double screenWidth = screenBounds.getWidth();
double screenHeight = screenBounds.getHeight();
if (statusBarHeight != 0.0) {
debug("IOSApplication", "Status bar is visible (height = " + statusBarHeight + ")");
screenHeight -= statusBarHeight;
} else {
debug("IOSApplication", "Status bar is not visible");
}
final int offsetX = 0;
final int offsetY = (int)Math.round(statusBarHeight);
final int width = (int)Math.round(screenWidth);
final int height = (int)Math.round(screenHeight);
final int backBufferWidth = (int)Math.round(screenWidth * pixelsPerPoint);
final int backBufferHeight = (int)Math.round(screenHeight * pixelsPerPoint);
debug("IOSApplication", "Computed bounds are x=" + offsetX + " y=" + offsetY + " w=" + width + " h=" + height + " bbW= "
+ backBufferWidth + " bbH= " + backBufferHeight);
return lastScreenBounds = new IOSScreenBounds(offsetX, offsetY, width, height, backBufferWidth, backBufferHeight);
}
/** @return area of screen in UIKit points on which libGDX draws, with 0,0 being upper left corner */
public IOSScreenBounds getScreenBounds () {
if (lastScreenBounds == null)
return computeBounds();
else
return lastScreenBounds;
}
final void didBecomeActive (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "resumed");
audio.didBecomeActive();
graphics.makeCurrent();
graphics.resume();
}
final void willEnterForeground (UIApplication uiApp) {
audio.willEnterForeground();
}
final void willResignActive (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "paused");
audio.willResignActive();
graphics.makeCurrent();
graphics.pause();
Gdx.gl.glFinish();
}
final void willTerminate (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "disposed");
audio.willTerminate();
graphics.makeCurrent();
Array<LifecycleListener> listeners = lifecycleListeners;
synchronized (listeners) {
for (LifecycleListener listener : listeners) {
listener.pause();
}
}
listener.dispose();
Gdx.gl.glFinish();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Input getInput () {
return input;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Net getNet () {
return net;
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public ApplicationType getType () {
return ApplicationType.iOS;
}
@Override
public int getVersion () {
return (int)NSProcessInfo.getSharedProcessInfo().getOperatingSystemVersion().getMajorVersion();
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return getJavaHeap();
}
@Override
public Preferences getPreferences (String name) {
File libraryPath = new File(System.getenv("HOME"), "Library");
File finalPath = new File(libraryPath, name + ".plist");
@SuppressWarnings("unchecked")
NSMutableDictionary<NSString, NSObject> nsDictionary = (NSMutableDictionary<NSString, NSObject>)NSMutableDictionary
.read(finalPath);
// if it fails to get an existing dictionary, create a new one.
if (nsDictionary == null) {
nsDictionary = new NSMutableDictionary<NSString, NSObject>();
nsDictionary.write(finalPath, false);
}
return new IOSPreferences(nsDictionary, finalPath.getAbsolutePath());
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
public void processRunnables () {
synchronized (runnables) {
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
}
for (int i = 0; i < executedRunnables.size; i++) {
try {
executedRunnables.get(i).run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@Override
public void exit () {
System.exit(0);
}
@Override
public Clipboard getClipboard () {
return new Clipboard() {
@Override
public void setContents (String content) {
UIPasteboard.getGeneralPasteboard().setString(content);
}
@Override
public boolean hasContents () {
return UIPasteboard.getGeneralPasteboard().hasStrings();
}
@Override
public String getContents () {
return UIPasteboard.getGeneralPasteboard().getString();
}
};
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
/** Add a listener to handle events from the libGDX root view controller
* @param listener The {#link IOSViewControllerListener} to add */
public void addViewControllerListener (IOSViewControllerListener listener) {
viewControllerListener = listener;
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-robovm-metalangle/src/com/badlogic/gdx/backends/iosrobovm/objectal/OALIOSAudio.java | /*DO NOT EDIT THIS FILE - it is machine generated*/
package com.badlogic.gdx.backends.iosrobovm.objectal;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.badlogic.gdx.backends.iosrobovm.IOSAudio;
import com.badlogic.gdx.backends.iosrobovm.IOSMusic;
import com.badlogic.gdx.backends.iosrobovm.IOSSound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** DO NOT EDIT THIS FILE - it is machine generated */
public class OALIOSAudio implements IOSAudio {
private final IOSApplicationConfiguration config;
public OALIOSAudio (IOSApplicationConfiguration config) {
this.config = config;
if (!config.useAudio) return;
OALSimpleAudio audio = OALSimpleAudio.sharedInstance();
if (audio != null) {
audio.setAllowIpod(config.allowIpod);
audio.setHonorSilentSwitch(!config.overrideRingerSwitch);
} else
Gdx.app.error("IOSAudio", "No OALSimpleAudio instance available, audio will not be availabe");
}
@Override
public AudioDevice newAudioDevice (int samplingRate, boolean isMono) {
// TODO Auto-generated method stub
return null;
}
@Override
public AudioRecorder newAudioRecorder (int samplingRate, boolean isMono) {
// TODO Auto-generated method stub
return null;
}
@Override
public Sound newSound (FileHandle fileHandle) {
return new IOSSound(fileHandle);
}
@Override
public Music newMusic (FileHandle fileHandle) {
String path = fileHandle.file().getPath().replace('\\', '/');
OALAudioTrack track = OALAudioTrack.create();
if (track != null) {
return new IOSMusic(track, path);
}
throw new GdxRuntimeException("Error creating music audio track");
}
@Override
public boolean switchOutputDevice (String deviceIdentifier) {
return true;
}
@Override
public String[] getAvailableOutputDevices () {
return new String[0];
}
@Override
public void didBecomeActive () {
// workaround for ObjectAL crash problem
// see: https://groups.google.com/g/objectal-for-iphone/c/ubRWltp_i1Q
forceEndInterruption();
if (config.allowIpod) {
OALSimpleAudio audio = OALSimpleAudio.sharedInstance();
if (audio != null) {
audio.setUseHardwareIfAvailable(false);
}
}
}
@Override
public void willEnterForeground () {
// workaround for ObjectAL crash problem
// see: https://groups.google.com/forum/?fromgroups=#!topic/objectal-for-iphone/ubRWltp_i1Q
forceEndInterruption();
}
@Override
public void willResignActive () {
}
@Override
public void willTerminate () {
}
private void forceEndInterruption () {
OALAudioSession audioSession = OALAudioSession.sharedInstance();
if (audioSession != null) {
audioSession.forceEndInterruption();
}
}
}
| /*DO NOT EDIT THIS FILE - it is machine generated*/
package com.badlogic.gdx.backends.iosrobovm.objectal;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.badlogic.gdx.backends.iosrobovm.IOSAudio;
import com.badlogic.gdx.backends.iosrobovm.IOSMusic;
import com.badlogic.gdx.backends.iosrobovm.IOSSound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** DO NOT EDIT THIS FILE - it is machine generated */
public class OALIOSAudio implements IOSAudio {
private final IOSApplicationConfiguration config;
public OALIOSAudio (IOSApplicationConfiguration config) {
this.config = config;
OALSimpleAudio audio = OALSimpleAudio.sharedInstance();
if (audio != null) {
audio.setAllowIpod(config.allowIpod);
audio.setHonorSilentSwitch(!config.overrideRingerSwitch);
} else
Gdx.app.error("IOSAudio", "No OALSimpleAudio instance available, audio will not be availabe");
}
@Override
public AudioDevice newAudioDevice (int samplingRate, boolean isMono) {
// TODO Auto-generated method stub
return null;
}
@Override
public AudioRecorder newAudioRecorder (int samplingRate, boolean isMono) {
// TODO Auto-generated method stub
return null;
}
@Override
public Sound newSound (FileHandle fileHandle) {
return new IOSSound(fileHandle);
}
@Override
public Music newMusic (FileHandle fileHandle) {
String path = fileHandle.file().getPath().replace('\\', '/');
OALAudioTrack track = OALAudioTrack.create();
if (track != null) {
return new IOSMusic(track, path);
}
throw new GdxRuntimeException("Error creating music audio track");
}
@Override
public boolean switchOutputDevice (String deviceIdentifier) {
return true;
}
@Override
public String[] getAvailableOutputDevices () {
return new String[0];
}
@Override
public void didBecomeActive () {
// workaround for ObjectAL crash problem
// see: https://groups.google.com/g/objectal-for-iphone/c/ubRWltp_i1Q
forceEndInterruption();
if (config.allowIpod) {
OALSimpleAudio audio = OALSimpleAudio.sharedInstance();
if (audio != null) {
audio.setUseHardwareIfAvailable(false);
}
}
}
@Override
public void willEnterForeground () {
// workaround for ObjectAL crash problem
// see: https://groups.google.com/forum/?fromgroups=#!topic/objectal-for-iphone/ubRWltp_i1Q
forceEndInterruption();
}
@Override
public void willResignActive () {
}
@Override
public void willTerminate () {
}
private void forceEndInterruption () {
OALAudioSession audioSession = OALAudioSession.sharedInstance();
if (audioSession != null) {
audioSession.forceEndInterruption();
}
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/IOSApplication.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.iosrobovm;
import java.io.File;
import com.badlogic.gdx.ApplicationLogger;
import com.badlogic.gdx.backends.iosrobovm.objectal.OALIOSAudio;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.foundation.NSMutableDictionary;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSProcessInfo;
import org.robovm.apple.foundation.NSString;
import org.robovm.apple.uikit.UIApplication;
import org.robovm.apple.uikit.UIApplicationDelegateAdapter;
import org.robovm.apple.uikit.UIApplicationLaunchOptions;
import org.robovm.apple.uikit.UIDevice;
import org.robovm.apple.uikit.UIUserInterfaceIdiom;
import org.robovm.apple.uikit.UIPasteboard;
import org.robovm.apple.uikit.UIScreen;
import org.robovm.apple.uikit.UIViewController;
import org.robovm.apple.uikit.UIWindow;
import org.robovm.rt.bro.Bro;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.LifecycleListener;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
public class IOSApplication implements Application {
public static abstract class Delegate extends UIApplicationDelegateAdapter {
private IOSApplication app;
protected abstract IOSApplication createApplication ();
@Override
public boolean didFinishLaunching (UIApplication application, UIApplicationLaunchOptions launchOptions) {
application.addStrongRef(this); // Prevent this from being GCed until the ObjC UIApplication is deallocated
this.app = createApplication();
return app.didFinishLaunching(application, launchOptions);
}
@Override
public void didBecomeActive (UIApplication application) {
app.didBecomeActive(application);
}
@Override
public void willEnterForeground (UIApplication application) {
app.willEnterForeground(application);
}
@Override
public void willResignActive (UIApplication application) {
app.willResignActive(application);
}
@Override
public void willTerminate (UIApplication application) {
app.willTerminate(application);
}
}
static final boolean IS_METALANGLE = false;
UIApplication uiApp;
UIWindow uiWindow;
ApplicationListener listener;
IOSViewControllerListener viewControllerListener;
IOSApplicationConfiguration config;
IOSGraphics graphics;
IOSAudio audio;
Files files;
IOSInput input;
IOSNet net;
int logLevel = Application.LOG_DEBUG;
ApplicationLogger applicationLogger;
/** The display scale factor (1.0f for normal; 2.0f to use retina coordinates/dimensions). */
float pixelsPerPoint;
private IOSScreenBounds lastScreenBounds = null;
Array<Runnable> runnables = new Array<Runnable>();
Array<Runnable> executedRunnables = new Array<Runnable>();
Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
public IOSApplication (ApplicationListener listener, IOSApplicationConfiguration config) {
this.listener = listener;
this.config = config;
}
final boolean didFinishLaunching (UIApplication uiApp, UIApplicationLaunchOptions options) {
setApplicationLogger(new IOSApplicationLogger());
Gdx.app = this;
this.uiApp = uiApp;
// enable or disable screen dimming
uiApp.setIdleTimerDisabled(config.preventScreenDimming);
Gdx.app.debug("IOSApplication", "iOS version: " + UIDevice.getCurrentDevice().getSystemVersion());
Gdx.app.debug("IOSApplication", "Running in " + (Bro.IS_64BIT ? "64-bit" : "32-bit") + " mode");
// iOS counts in "points" instead of pixels. Points are logical pixels
pixelsPerPoint = (float)UIScreen.getMainScreen().getNativeScale();
Gdx.app.debug("IOSApplication", "Pixels per point: " + pixelsPerPoint);
this.uiWindow = new UIWindow(UIScreen.getMainScreen().getBounds());
this.uiWindow.makeKeyAndVisible();
uiApp.getDelegate().setWindow(uiWindow);
// setup libgdx
this.input = createInput();
this.graphics = createGraphics();
Gdx.gl = Gdx.gl20 = graphics.gl20;
Gdx.gl30 = graphics.gl30;
this.files = createFiles();
this.audio = createAudio(config);
this.net = new IOSNet(this, config);
Gdx.files = this.files;
Gdx.graphics = this.graphics;
Gdx.audio = this.audio;
Gdx.input = this.input;
Gdx.net = this.net;
this.input.setupPeripherals();
this.uiWindow.setRootViewController(this.graphics.viewController);
this.graphics.updateSafeInsets();
Gdx.app.debug("IOSApplication", "created");
listener.create();
listener.resize(this.graphics.getWidth(), this.graphics.getHeight());
// make sure the OpenGL view has contents before displaying it
this.graphics.view.display();
return true;
}
protected Files createFiles () {
return new IOSFiles();
}
protected IOSAudio createAudio (IOSApplicationConfiguration config) {
return new OALIOSAudio(config);
}
protected IOSGraphics createGraphics () {
return new IOSGraphics(this, config, input, config.useGL30);
}
protected IOSUIViewController createUIViewController (IOSGraphics graphics) {
return new IOSUIViewController(this, graphics);
}
protected IOSInput createInput () {
return new DefaultIOSInput(this);
}
/** Returns device ppi using a best guess approach when device is unknown. Overwrite to customize strategy. */
protected int guessUnknownPpi () {
int ppi;
if (UIDevice.getCurrentDevice().getUserInterfaceIdiom() == UIUserInterfaceIdiom.Pad)
ppi = 132 * (int)pixelsPerPoint;
else
ppi = 164 * (int)pixelsPerPoint;
error("IOSApplication", "Device PPI unknown. PPI value has been guessed to " + ppi + " but may be wrong");
return ppi;
}
/** Return the UI view controller of IOSApplication
* @return the view controller of IOSApplication */
public UIViewController getUIViewController () {
return graphics.viewController;
}
/** Return the UI Window of IOSApplication
* @return the window */
public UIWindow getUIWindow () {
return uiWindow;
}
/** @see IOSScreenBounds for detailed explanation
* @return logical dimensions of space we draw to, adjusted for device orientation */
protected IOSScreenBounds computeBounds () {
CGRect screenBounds = uiWindow.getBounds();
final CGRect statusBarFrame = uiApp.getStatusBarFrame();
double statusBarHeight = statusBarFrame.getHeight();
double screenWidth = screenBounds.getWidth();
double screenHeight = screenBounds.getHeight();
if (statusBarHeight != 0.0) {
debug("IOSApplication", "Status bar is visible (height = " + statusBarHeight + ")");
screenHeight -= statusBarHeight;
} else {
debug("IOSApplication", "Status bar is not visible");
}
final int offsetX = 0;
final int offsetY = (int)Math.round(statusBarHeight);
final int width = (int)Math.round(screenWidth);
final int height = (int)Math.round(screenHeight);
final int backBufferWidth = (int)Math.round(screenWidth * pixelsPerPoint);
final int backBufferHeight = (int)Math.round(screenHeight * pixelsPerPoint);
debug("IOSApplication", "Computed bounds are x=" + offsetX + " y=" + offsetY + " w=" + width + " h=" + height + " bbW= "
+ backBufferWidth + " bbH= " + backBufferHeight);
return lastScreenBounds = new IOSScreenBounds(offsetX, offsetY, width, height, backBufferWidth, backBufferHeight);
}
/** @return area of screen in UIKit points on which libGDX draws, with 0,0 being upper left corner */
public IOSScreenBounds getScreenBounds () {
if (lastScreenBounds == null)
return computeBounds();
else
return lastScreenBounds;
}
final void didBecomeActive (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "resumed");
audio.didBecomeActive();
graphics.makeCurrent();
graphics.resume();
}
final void willEnterForeground (UIApplication uiApp) {
audio.willEnterForeground();
}
final void willResignActive (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "paused");
audio.willResignActive();
graphics.makeCurrent();
graphics.pause();
Gdx.gl.glFinish();
}
final void willTerminate (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "disposed");
audio.willTerminate();
graphics.makeCurrent();
Array<LifecycleListener> listeners = lifecycleListeners;
synchronized (listeners) {
for (LifecycleListener listener : listeners) {
listener.pause();
}
}
listener.dispose();
Gdx.gl.glFinish();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Input getInput () {
return input;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Net getNet () {
return net;
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public ApplicationType getType () {
return ApplicationType.iOS;
}
@Override
public int getVersion () {
return (int)NSProcessInfo.getSharedProcessInfo().getOperatingSystemVersion().getMajorVersion();
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return getJavaHeap();
}
@Override
public Preferences getPreferences (String name) {
File libraryPath = new File(System.getenv("HOME"), "Library");
File finalPath = new File(libraryPath, name + ".plist");
@SuppressWarnings("unchecked")
NSMutableDictionary<NSString, NSObject> nsDictionary = (NSMutableDictionary<NSString, NSObject>)NSMutableDictionary
.read(finalPath);
// if it fails to get an existing dictionary, create a new one.
if (nsDictionary == null) {
nsDictionary = new NSMutableDictionary<NSString, NSObject>();
nsDictionary.write(finalPath, false);
}
return new IOSPreferences(nsDictionary, finalPath.getAbsolutePath());
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
public void processRunnables () {
synchronized (runnables) {
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
}
for (int i = 0; i < executedRunnables.size; i++) {
try {
executedRunnables.get(i).run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@Override
public void exit () {
System.exit(0);
}
@Override
public Clipboard getClipboard () {
return new Clipboard() {
@Override
public void setContents (String content) {
UIPasteboard.getGeneralPasteboard().setString(content);
}
@Override
public boolean hasContents () {
return UIPasteboard.getGeneralPasteboard().hasStrings();
}
@Override
public String getContents () {
return UIPasteboard.getGeneralPasteboard().getString();
}
};
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
/** Add a listener to handle events from the libGDX root view controller
* @param listener The {#link IOSViewControllerListener} to add */
public void addViewControllerListener (IOSViewControllerListener listener) {
viewControllerListener = listener;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.iosrobovm;
import java.io.File;
import com.badlogic.gdx.ApplicationLogger;
import com.badlogic.gdx.backends.iosrobovm.objectal.OALIOSAudio;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.foundation.NSMutableDictionary;
import org.robovm.apple.foundation.NSObject;
import org.robovm.apple.foundation.NSProcessInfo;
import org.robovm.apple.foundation.NSString;
import org.robovm.apple.uikit.UIApplication;
import org.robovm.apple.uikit.UIApplicationDelegateAdapter;
import org.robovm.apple.uikit.UIApplicationLaunchOptions;
import org.robovm.apple.uikit.UIDevice;
import org.robovm.apple.uikit.UIUserInterfaceIdiom;
import org.robovm.apple.uikit.UIPasteboard;
import org.robovm.apple.uikit.UIScreen;
import org.robovm.apple.uikit.UIViewController;
import org.robovm.apple.uikit.UIWindow;
import org.robovm.rt.bro.Bro;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.LifecycleListener;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
public class IOSApplication implements Application {
public static abstract class Delegate extends UIApplicationDelegateAdapter {
private IOSApplication app;
protected abstract IOSApplication createApplication ();
@Override
public boolean didFinishLaunching (UIApplication application, UIApplicationLaunchOptions launchOptions) {
application.addStrongRef(this); // Prevent this from being GCed until the ObjC UIApplication is deallocated
this.app = createApplication();
return app.didFinishLaunching(application, launchOptions);
}
@Override
public void didBecomeActive (UIApplication application) {
app.didBecomeActive(application);
}
@Override
public void willEnterForeground (UIApplication application) {
app.willEnterForeground(application);
}
@Override
public void willResignActive (UIApplication application) {
app.willResignActive(application);
}
@Override
public void willTerminate (UIApplication application) {
app.willTerminate(application);
}
}
static final boolean IS_METALANGLE = false;
UIApplication uiApp;
UIWindow uiWindow;
ApplicationListener listener;
IOSViewControllerListener viewControllerListener;
IOSApplicationConfiguration config;
IOSGraphics graphics;
IOSAudio audio;
Files files;
IOSInput input;
IOSNet net;
int logLevel = Application.LOG_DEBUG;
ApplicationLogger applicationLogger;
/** The display scale factor (1.0f for normal; 2.0f to use retina coordinates/dimensions). */
float pixelsPerPoint;
private IOSScreenBounds lastScreenBounds = null;
Array<Runnable> runnables = new Array<Runnable>();
Array<Runnable> executedRunnables = new Array<Runnable>();
Array<LifecycleListener> lifecycleListeners = new Array<LifecycleListener>();
public IOSApplication (ApplicationListener listener, IOSApplicationConfiguration config) {
this.listener = listener;
this.config = config;
}
final boolean didFinishLaunching (UIApplication uiApp, UIApplicationLaunchOptions options) {
setApplicationLogger(new IOSApplicationLogger());
Gdx.app = this;
this.uiApp = uiApp;
// enable or disable screen dimming
uiApp.setIdleTimerDisabled(config.preventScreenDimming);
Gdx.app.debug("IOSApplication", "iOS version: " + UIDevice.getCurrentDevice().getSystemVersion());
Gdx.app.debug("IOSApplication", "Running in " + (Bro.IS_64BIT ? "64-bit" : "32-bit") + " mode");
// iOS counts in "points" instead of pixels. Points are logical pixels
pixelsPerPoint = (float)UIScreen.getMainScreen().getNativeScale();
Gdx.app.debug("IOSApplication", "Pixels per point: " + pixelsPerPoint);
this.uiWindow = new UIWindow(UIScreen.getMainScreen().getBounds());
this.uiWindow.makeKeyAndVisible();
uiApp.getDelegate().setWindow(uiWindow);
// setup libgdx
this.input = createInput();
this.graphics = createGraphics();
Gdx.gl = Gdx.gl20 = graphics.gl20;
Gdx.gl30 = graphics.gl30;
this.files = createFiles();
this.audio = createAudio(config);
this.net = new IOSNet(this, config);
Gdx.files = this.files;
Gdx.graphics = this.graphics;
Gdx.audio = this.audio;
Gdx.input = this.input;
Gdx.net = this.net;
this.input.setupPeripherals();
this.uiWindow.setRootViewController(this.graphics.viewController);
this.graphics.updateSafeInsets();
Gdx.app.debug("IOSApplication", "created");
listener.create();
listener.resize(this.graphics.getWidth(), this.graphics.getHeight());
// make sure the OpenGL view has contents before displaying it
this.graphics.view.display();
return true;
}
protected Files createFiles () {
return new IOSFiles();
}
protected IOSAudio createAudio (IOSApplicationConfiguration config) {
if (config.useAudio)
return new OALIOSAudio(config);
else
return new DisabledIOSAudio();
}
protected IOSGraphics createGraphics () {
return new IOSGraphics(this, config, input, config.useGL30);
}
protected IOSUIViewController createUIViewController (IOSGraphics graphics) {
return new IOSUIViewController(this, graphics);
}
protected IOSInput createInput () {
return new DefaultIOSInput(this);
}
/** Returns device ppi using a best guess approach when device is unknown. Overwrite to customize strategy. */
protected int guessUnknownPpi () {
int ppi;
if (UIDevice.getCurrentDevice().getUserInterfaceIdiom() == UIUserInterfaceIdiom.Pad)
ppi = 132 * (int)pixelsPerPoint;
else
ppi = 164 * (int)pixelsPerPoint;
error("IOSApplication", "Device PPI unknown. PPI value has been guessed to " + ppi + " but may be wrong");
return ppi;
}
/** Return the UI view controller of IOSApplication
* @return the view controller of IOSApplication */
public UIViewController getUIViewController () {
return graphics.viewController;
}
/** Return the UI Window of IOSApplication
* @return the window */
public UIWindow getUIWindow () {
return uiWindow;
}
/** @see IOSScreenBounds for detailed explanation
* @return logical dimensions of space we draw to, adjusted for device orientation */
protected IOSScreenBounds computeBounds () {
CGRect screenBounds = uiWindow.getBounds();
final CGRect statusBarFrame = uiApp.getStatusBarFrame();
double statusBarHeight = statusBarFrame.getHeight();
double screenWidth = screenBounds.getWidth();
double screenHeight = screenBounds.getHeight();
if (statusBarHeight != 0.0) {
debug("IOSApplication", "Status bar is visible (height = " + statusBarHeight + ")");
screenHeight -= statusBarHeight;
} else {
debug("IOSApplication", "Status bar is not visible");
}
final int offsetX = 0;
final int offsetY = (int)Math.round(statusBarHeight);
final int width = (int)Math.round(screenWidth);
final int height = (int)Math.round(screenHeight);
final int backBufferWidth = (int)Math.round(screenWidth * pixelsPerPoint);
final int backBufferHeight = (int)Math.round(screenHeight * pixelsPerPoint);
debug("IOSApplication", "Computed bounds are x=" + offsetX + " y=" + offsetY + " w=" + width + " h=" + height + " bbW= "
+ backBufferWidth + " bbH= " + backBufferHeight);
return lastScreenBounds = new IOSScreenBounds(offsetX, offsetY, width, height, backBufferWidth, backBufferHeight);
}
/** @return area of screen in UIKit points on which libGDX draws, with 0,0 being upper left corner */
public IOSScreenBounds getScreenBounds () {
if (lastScreenBounds == null)
return computeBounds();
else
return lastScreenBounds;
}
final void didBecomeActive (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "resumed");
audio.didBecomeActive();
graphics.makeCurrent();
graphics.resume();
}
final void willEnterForeground (UIApplication uiApp) {
audio.willEnterForeground();
}
final void willResignActive (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "paused");
audio.willResignActive();
graphics.makeCurrent();
graphics.pause();
Gdx.gl.glFinish();
}
final void willTerminate (UIApplication uiApp) {
Gdx.app.debug("IOSApplication", "disposed");
audio.willTerminate();
graphics.makeCurrent();
Array<LifecycleListener> listeners = lifecycleListeners;
synchronized (listeners) {
for (LifecycleListener listener : listeners) {
listener.pause();
}
}
listener.dispose();
Gdx.gl.glFinish();
}
@Override
public ApplicationListener getApplicationListener () {
return listener;
}
@Override
public Graphics getGraphics () {
return graphics;
}
@Override
public Audio getAudio () {
return audio;
}
@Override
public Input getInput () {
return input;
}
@Override
public Files getFiles () {
return files;
}
@Override
public Net getNet () {
return net;
}
@Override
public void debug (String tag, String message) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message);
}
@Override
public void debug (String tag, String message, Throwable exception) {
if (logLevel >= LOG_DEBUG) getApplicationLogger().debug(tag, message, exception);
}
@Override
public void log (String tag, String message) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message);
}
@Override
public void log (String tag, String message, Throwable exception) {
if (logLevel >= LOG_INFO) getApplicationLogger().log(tag, message, exception);
}
@Override
public void error (String tag, String message) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message);
}
@Override
public void error (String tag, String message, Throwable exception) {
if (logLevel >= LOG_ERROR) getApplicationLogger().error(tag, message, exception);
}
@Override
public void setLogLevel (int logLevel) {
this.logLevel = logLevel;
}
@Override
public int getLogLevel () {
return logLevel;
}
@Override
public void setApplicationLogger (ApplicationLogger applicationLogger) {
this.applicationLogger = applicationLogger;
}
@Override
public ApplicationLogger getApplicationLogger () {
return applicationLogger;
}
@Override
public ApplicationType getType () {
return ApplicationType.iOS;
}
@Override
public int getVersion () {
return (int)NSProcessInfo.getSharedProcessInfo().getOperatingSystemVersion().getMajorVersion();
}
@Override
public long getJavaHeap () {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getNativeHeap () {
return getJavaHeap();
}
@Override
public Preferences getPreferences (String name) {
File libraryPath = new File(System.getenv("HOME"), "Library");
File finalPath = new File(libraryPath, name + ".plist");
@SuppressWarnings("unchecked")
NSMutableDictionary<NSString, NSObject> nsDictionary = (NSMutableDictionary<NSString, NSObject>)NSMutableDictionary
.read(finalPath);
// if it fails to get an existing dictionary, create a new one.
if (nsDictionary == null) {
nsDictionary = new NSMutableDictionary<NSString, NSObject>();
nsDictionary.write(finalPath, false);
}
return new IOSPreferences(nsDictionary, finalPath.getAbsolutePath());
}
@Override
public void postRunnable (Runnable runnable) {
synchronized (runnables) {
runnables.add(runnable);
Gdx.graphics.requestRendering();
}
}
public void processRunnables () {
synchronized (runnables) {
executedRunnables.clear();
executedRunnables.addAll(runnables);
runnables.clear();
}
for (int i = 0; i < executedRunnables.size; i++) {
try {
executedRunnables.get(i).run();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
@Override
public void exit () {
System.exit(0);
}
@Override
public Clipboard getClipboard () {
return new Clipboard() {
@Override
public void setContents (String content) {
UIPasteboard.getGeneralPasteboard().setString(content);
}
@Override
public boolean hasContents () {
return UIPasteboard.getGeneralPasteboard().hasStrings();
}
@Override
public String getContents () {
return UIPasteboard.getGeneralPasteboard().getString();
}
};
}
@Override
public void addLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.add(listener);
}
}
@Override
public void removeLifecycleListener (LifecycleListener listener) {
synchronized (lifecycleListeners) {
lifecycleListeners.removeValue(listener, true);
}
}
/** Add a listener to handle events from the libGDX root view controller
* @param listener The {#link IOSViewControllerListener} to add */
public void addViewControllerListener (IOSViewControllerListener listener) {
viewControllerListener = listener;
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-robovm/src/com/badlogic/gdx/backends/iosrobovm/objectal/OALIOSAudio.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.iosrobovm.objectal;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.badlogic.gdx.backends.iosrobovm.IOSAudio;
import com.badlogic.gdx.backends.iosrobovm.IOSMusic;
import com.badlogic.gdx.backends.iosrobovm.IOSSound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class OALIOSAudio implements IOSAudio {
private final IOSApplicationConfiguration config;
public OALIOSAudio (IOSApplicationConfiguration config) {
this.config = config;
if (!config.useAudio) return;
OALSimpleAudio audio = OALSimpleAudio.sharedInstance();
if (audio != null) {
audio.setAllowIpod(config.allowIpod);
audio.setHonorSilentSwitch(!config.overrideRingerSwitch);
} else
Gdx.app.error("IOSAudio", "No OALSimpleAudio instance available, audio will not be availabe");
}
@Override
public AudioDevice newAudioDevice (int samplingRate, boolean isMono) {
// TODO Auto-generated method stub
return null;
}
@Override
public AudioRecorder newAudioRecorder (int samplingRate, boolean isMono) {
// TODO Auto-generated method stub
return null;
}
@Override
public Sound newSound (FileHandle fileHandle) {
return new IOSSound(fileHandle);
}
@Override
public Music newMusic (FileHandle fileHandle) {
String path = fileHandle.file().getPath().replace('\\', '/');
OALAudioTrack track = OALAudioTrack.create();
if (track != null) {
return new IOSMusic(track, path);
}
throw new GdxRuntimeException("Error creating music audio track");
}
@Override
public boolean switchOutputDevice (String deviceIdentifier) {
return true;
}
@Override
public String[] getAvailableOutputDevices () {
return new String[0];
}
@Override
public void didBecomeActive () {
// workaround for ObjectAL crash problem
// see: https://groups.google.com/g/objectal-for-iphone/c/ubRWltp_i1Q
forceEndInterruption();
if (config.allowIpod) {
OALSimpleAudio audio = OALSimpleAudio.sharedInstance();
if (audio != null) {
audio.setUseHardwareIfAvailable(false);
}
}
}
@Override
public void willEnterForeground () {
// workaround for ObjectAL crash problem
// see: https://groups.google.com/forum/?fromgroups=#!topic/objectal-for-iphone/ubRWltp_i1Q
forceEndInterruption();
}
@Override
public void willResignActive () {
}
@Override
public void willTerminate () {
}
private void forceEndInterruption () {
OALAudioSession audioSession = OALAudioSession.sharedInstance();
if (audioSession != null) {
audioSession.forceEndInterruption();
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.iosrobovm.objectal;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.badlogic.gdx.backends.iosrobovm.IOSAudio;
import com.badlogic.gdx.backends.iosrobovm.IOSMusic;
import com.badlogic.gdx.backends.iosrobovm.IOSSound;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class OALIOSAudio implements IOSAudio {
private final IOSApplicationConfiguration config;
public OALIOSAudio (IOSApplicationConfiguration config) {
this.config = config;
OALSimpleAudio audio = OALSimpleAudio.sharedInstance();
if (audio != null) {
audio.setAllowIpod(config.allowIpod);
audio.setHonorSilentSwitch(!config.overrideRingerSwitch);
} else
Gdx.app.error("IOSAudio", "No OALSimpleAudio instance available, audio will not be availabe");
}
@Override
public AudioDevice newAudioDevice (int samplingRate, boolean isMono) {
// TODO Auto-generated method stub
return null;
}
@Override
public AudioRecorder newAudioRecorder (int samplingRate, boolean isMono) {
// TODO Auto-generated method stub
return null;
}
@Override
public Sound newSound (FileHandle fileHandle) {
return new IOSSound(fileHandle);
}
@Override
public Music newMusic (FileHandle fileHandle) {
String path = fileHandle.file().getPath().replace('\\', '/');
OALAudioTrack track = OALAudioTrack.create();
if (track != null) {
return new IOSMusic(track, path);
}
throw new GdxRuntimeException("Error creating music audio track");
}
@Override
public boolean switchOutputDevice (String deviceIdentifier) {
return true;
}
@Override
public String[] getAvailableOutputDevices () {
return new String[0];
}
@Override
public void didBecomeActive () {
// workaround for ObjectAL crash problem
// see: https://groups.google.com/g/objectal-for-iphone/c/ubRWltp_i1Q
forceEndInterruption();
if (config.allowIpod) {
OALSimpleAudio audio = OALSimpleAudio.sharedInstance();
if (audio != null) {
audio.setUseHardwareIfAvailable(false);
}
}
}
@Override
public void willEnterForeground () {
// workaround for ObjectAL crash problem
// see: https://groups.google.com/forum/?fromgroups=#!topic/objectal-for-iphone/ubRWltp_i1Q
forceEndInterruption();
}
@Override
public void willResignActive () {
}
@Override
public void willTerminate () {
}
private void forceEndInterruption () {
OALAudioSession audioSession = OALAudioSession.sharedInstance();
if (audioSession != null) {
audioSession.forceEndInterruption();
}
}
}
| 1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/preloader/LoaderCallback.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt.preloader;
public interface LoaderCallback<T> {
public void success (T result);
public void error ();
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt.preloader;
public interface LoaderCallback<T> {
public void success (T result);
public void error ();
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapTest.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import java.nio.ByteBuffer;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.BufferUtils;
public class PixmapTest extends GdxTest {
Pixmap pixmap;
Texture texture;
SpriteBatch batch;
TextureRegion region;
Pixmap pixmapCustom;
Texture textureCustom;
TextureRegion regionCustom;
public void create () {
// Create an empty dynamic pixmap
pixmap = new Pixmap(800, 480, Pixmap.Format.RGBA8888);
pixmapCustom = new Pixmap(256, 256, Pixmap.Format.RGBA8888);
ByteBuffer buffer = BufferUtils.newByteBuffer(pixmapCustom.getWidth() * pixmapCustom.getHeight() * 4);
for (int y = 0; y < pixmapCustom.getHeight(); y++) {
for (int x = 0; x < pixmapCustom.getWidth(); x++) {
buffer.put((byte)x);
buffer.put((byte)y);
buffer.put((byte)0);
buffer.put((byte)255);
}
}
buffer.flip();
pixmapCustom.setPixels(buffer);
textureCustom = new Texture(pixmapCustom);
regionCustom = new TextureRegion(textureCustom);
// Create a texture to contain the pixmap
texture = new Texture(1024, 1024, Pixmap.Format.RGBA8888); // Pixmap.Format.RGBA8888);
texture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Linear);
texture.setWrap(Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge);
pixmap.setColor(1.0f, 0.0f, 0.0f, 1.0f); // Red
pixmap.drawLine(0, 0, 100, 100);
pixmap.setColor(0.0f, 0.0f, 1.0f, 1.0f); // Blue
pixmap.drawLine(100, 100, 200, 0);
pixmap.setColor(0.0f, 1.0f, 0.0f, 1.0f); // Green
pixmap.drawLine(100, 0, 100, 100);
pixmap.setColor(1.0f, 1.0f, 1.0f, 1.0f); // White
pixmap.drawCircle(400, 300, 100);
// Blit the composited overlay to a texture
texture.draw(pixmap, 0, 0);
region = new TextureRegion(texture, 0, 0, 800, 480);
batch = new SpriteBatch();
Pixmap pixmap = new Pixmap(512, 1024, Pixmap.Format.RGBA8888);
for (int y = 0; y < pixmap.getHeight(); y++) { // 1024
for (int x = 0; x < pixmap.getWidth(); x++) { // 512
pixmap.getPixel(x, y);
}
}
pixmap.dispose();
}
public void render () {
ScreenUtils.clear(0.6f, 0.6f, 0.6f, 1);
batch.begin();
batch.draw(region, 0, 0);
batch.draw(regionCustom, 0, 0);
batch.end();
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import java.nio.ByteBuffer;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.ScreenUtils;
import com.badlogic.gdx.utils.BufferUtils;
public class PixmapTest extends GdxTest {
Pixmap pixmap;
Texture texture;
SpriteBatch batch;
TextureRegion region;
Pixmap pixmapCustom;
Texture textureCustom;
TextureRegion regionCustom;
public void create () {
// Create an empty dynamic pixmap
pixmap = new Pixmap(800, 480, Pixmap.Format.RGBA8888);
pixmapCustom = new Pixmap(256, 256, Pixmap.Format.RGBA8888);
ByteBuffer buffer = BufferUtils.newByteBuffer(pixmapCustom.getWidth() * pixmapCustom.getHeight() * 4);
for (int y = 0; y < pixmapCustom.getHeight(); y++) {
for (int x = 0; x < pixmapCustom.getWidth(); x++) {
buffer.put((byte)x);
buffer.put((byte)y);
buffer.put((byte)0);
buffer.put((byte)255);
}
}
buffer.flip();
pixmapCustom.setPixels(buffer);
textureCustom = new Texture(pixmapCustom);
regionCustom = new TextureRegion(textureCustom);
// Create a texture to contain the pixmap
texture = new Texture(1024, 1024, Pixmap.Format.RGBA8888); // Pixmap.Format.RGBA8888);
texture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Linear);
texture.setWrap(Texture.TextureWrap.ClampToEdge, Texture.TextureWrap.ClampToEdge);
pixmap.setColor(1.0f, 0.0f, 0.0f, 1.0f); // Red
pixmap.drawLine(0, 0, 100, 100);
pixmap.setColor(0.0f, 0.0f, 1.0f, 1.0f); // Blue
pixmap.drawLine(100, 100, 200, 0);
pixmap.setColor(0.0f, 1.0f, 0.0f, 1.0f); // Green
pixmap.drawLine(100, 0, 100, 100);
pixmap.setColor(1.0f, 1.0f, 1.0f, 1.0f); // White
pixmap.drawCircle(400, 300, 100);
// Blit the composited overlay to a texture
texture.draw(pixmap, 0, 0);
region = new TextureRegion(texture, 0, 0, 800, 480);
batch = new SpriteBatch();
Pixmap pixmap = new Pixmap(512, 1024, Pixmap.Format.RGBA8888);
for (int y = 0; y < pixmap.getHeight(); y++) { // 1024
for (int x = 0; x < pixmap.getWidth(); x++) { // 512
pixmap.getPixel(x, y);
}
}
pixmap.dispose();
}
public void render () {
ScreenUtils.clear(0.6f, 0.6f, 0.6f, 1);
batch.begin();
batch.draw(region, 0, 0);
batch.draw(regionCustom, 0, 0);
batch.end();
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/preloader/AssetFilter.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt.preloader;
/** Interface used by the PreloaderBundleGenerator to decide whether an asset found in the gdx.assetpath should be included in the
* war/ folder or not. Also used to determine the type of an asset. Default implementation can be found in DefaultAssetFilter, and
* is used if user doesn't specify a custom filter in the module gwt.xml file.
* @author mzechner */
public interface AssetFilter {
public enum AssetType {
Image("i"), Audio("a"), Text("t"), Binary("b"), Directory("d");
public final String code;
private AssetType (String code) {
this.code = code;
}
}
/** @param file the file to filter
* @param isDirectory whether the file is a directory
* @return whether to include the file in the war/ folder or not. */
public boolean accept (String file, boolean isDirectory);
/** @param file the file to filter
* @return whether to preload the file, or to lazy load it via AssetManager */
public boolean preload (String file);
/** @param file the file to get the type for
* @return the type of the file, one of {@link AssetType} */
public AssetType getType (String file);
/** @param file the file to get the bundle name for
* @return the name of the bundle to which this file should be added */
public String getBundleName (String file);
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt.preloader;
/** Interface used by the PreloaderBundleGenerator to decide whether an asset found in the gdx.assetpath should be included in the
* war/ folder or not. Also used to determine the type of an asset. Default implementation can be found in DefaultAssetFilter, and
* is used if user doesn't specify a custom filter in the module gwt.xml file.
* @author mzechner */
public interface AssetFilter {
public enum AssetType {
Image("i"), Audio("a"), Text("t"), Binary("b"), Directory("d");
public final String code;
private AssetType (String code) {
this.code = code;
}
}
/** @param file the file to filter
* @param isDirectory whether the file is a directory
* @return whether to include the file in the war/ folder or not. */
public boolean accept (String file, boolean isDirectory);
/** @param file the file to filter
* @return whether to preload the file, or to lazy load it via AssetManager */
public boolean preload (String file);
/** @param file the file to get the type for
* @return the type of the file, one of {@link AssetType} */
public AssetType getType (String file);
/** @param file the file to get the bundle name for
* @return the name of the bundle to which this file should be added */
public String getBundleName (String file);
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/collision/broadphase/DynamicTreeFlatNodes.java | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.collision.broadphase;
import org.jbox2d.callbacks.DebugDraw;
import org.jbox2d.callbacks.TreeCallback;
import org.jbox2d.callbacks.TreeRayCastCallback;
import org.jbox2d.collision.AABB;
import org.jbox2d.collision.RayCastInput;
import org.jbox2d.common.BufferUtils;
import org.jbox2d.common.Color3f;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Vec2;
public class DynamicTreeFlatNodes implements BroadPhaseStrategy {
public static final int MAX_STACK_SIZE = 64;
public static final int NULL_NODE = -1;
public static final int INITIAL_BUFFER_LENGTH = 16;
public int m_root;
public AABB[] m_aabb;
public Object[] m_userData;
protected int[] m_parent;
protected int[] m_child1;
protected int[] m_child2;
protected int[] m_height;
private int m_nodeCount;
private int m_nodeCapacity;
private int m_freeList;
private final Vec2[] drawVecs = new Vec2[4];
public DynamicTreeFlatNodes () {
m_root = NULL_NODE;
m_nodeCount = 0;
m_nodeCapacity = 16;
expandBuffers(0, m_nodeCapacity);
for (int i = 0; i < drawVecs.length; i++) {
drawVecs[i] = new Vec2();
}
}
private void expandBuffers (int oldSize, int newSize) {
m_aabb = BufferUtils.reallocateBuffer(AABB.class, m_aabb, oldSize, newSize);
m_userData = BufferUtils.reallocateBuffer(Object.class, m_userData, oldSize, newSize);
m_parent = BufferUtils.reallocateBuffer(m_parent, oldSize, newSize);
m_child1 = BufferUtils.reallocateBuffer(m_child1, oldSize, newSize);
m_child2 = BufferUtils.reallocateBuffer(m_child2, oldSize, newSize);
m_height = BufferUtils.reallocateBuffer(m_height, oldSize, newSize);
// Build a linked list for the free list.
for (int i = oldSize; i < newSize; i++) {
m_aabb[i] = new AABB();
m_parent[i] = (i == newSize - 1) ? NULL_NODE : i + 1;
m_height[i] = -1;
m_child1[i] = -1;
m_child2[i] = -1;
}
m_freeList = oldSize;
}
@Override
public final int createProxy (final AABB aabb, Object userData) {
final int node = allocateNode();
// Fatten the aabb
final AABB nodeAABB = m_aabb[node];
nodeAABB.lowerBound.x = aabb.lowerBound.x - Settings.aabbExtension;
nodeAABB.lowerBound.y = aabb.lowerBound.y - Settings.aabbExtension;
nodeAABB.upperBound.x = aabb.upperBound.x + Settings.aabbExtension;
nodeAABB.upperBound.y = aabb.upperBound.y + Settings.aabbExtension;
m_userData[node] = userData;
insertLeaf(node);
return node;
}
@Override
public final void destroyProxy (int proxyId) {
assert (0 <= proxyId && proxyId < m_nodeCapacity);
assert (m_child1[proxyId] == NULL_NODE);
removeLeaf(proxyId);
freeNode(proxyId);
}
@Override
public final boolean moveProxy (int proxyId, final AABB aabb, Vec2 displacement) {
assert (0 <= proxyId && proxyId < m_nodeCapacity);
final int node = proxyId;
assert (m_child1[node] == NULL_NODE);
final AABB nodeAABB = m_aabb[node];
// if (nodeAABB.contains(aabb)) {
if (nodeAABB.lowerBound.x <= aabb.lowerBound.x && nodeAABB.lowerBound.y <= aabb.lowerBound.y
&& aabb.upperBound.x <= nodeAABB.upperBound.x && aabb.upperBound.y <= nodeAABB.upperBound.y) {
return false;
}
removeLeaf(node);
// Extend AABB
final Vec2 lowerBound = nodeAABB.lowerBound;
final Vec2 upperBound = nodeAABB.upperBound;
lowerBound.x = aabb.lowerBound.x - Settings.aabbExtension;
lowerBound.y = aabb.lowerBound.y - Settings.aabbExtension;
upperBound.x = aabb.upperBound.x + Settings.aabbExtension;
upperBound.y = aabb.upperBound.y + Settings.aabbExtension;
// Predict AABB displacement.
final float dx = displacement.x * Settings.aabbMultiplier;
final float dy = displacement.y * Settings.aabbMultiplier;
if (dx < 0.0f) {
lowerBound.x += dx;
} else {
upperBound.x += dx;
}
if (dy < 0.0f) {
lowerBound.y += dy;
} else {
upperBound.y += dy;
}
insertLeaf(proxyId);
return true;
}
@Override
public final Object getUserData (int proxyId) {
assert (0 <= proxyId && proxyId < m_nodeCount);
return m_userData[proxyId];
}
@Override
public final AABB getFatAABB (int proxyId) {
assert (0 <= proxyId && proxyId < m_nodeCount);
return m_aabb[proxyId];
}
private int[] nodeStack = new int[20];
private int nodeStackIndex;
@Override
public final void query (TreeCallback callback, AABB aabb) {
nodeStackIndex = 0;
nodeStack[nodeStackIndex++] = m_root;
while (nodeStackIndex > 0) {
int node = nodeStack[--nodeStackIndex];
if (node == NULL_NODE) {
continue;
}
if (AABB.testOverlap(m_aabb[node], aabb)) {
int child1 = m_child1[node];
if (child1 == NULL_NODE) {
boolean proceed = callback.treeCallback(node);
if (!proceed) {
return;
}
} else {
if (nodeStack.length - nodeStackIndex - 2 <= 0) {
nodeStack = BufferUtils.reallocateBuffer(nodeStack, nodeStack.length, nodeStack.length * 2);
}
nodeStack[nodeStackIndex++] = child1;
nodeStack[nodeStackIndex++] = m_child2[node];
}
}
}
}
private final Vec2 r = new Vec2();
private final AABB aabb = new AABB();
private final RayCastInput subInput = new RayCastInput();
@Override
public void raycast (TreeRayCastCallback callback, RayCastInput input) {
final Vec2 p1 = input.p1;
final Vec2 p2 = input.p2;
float p1x = p1.x, p2x = p2.x, p1y = p1.y, p2y = p2.y;
float vx, vy;
float rx, ry;
float absVx, absVy;
float cx, cy;
float hx, hy;
float tempx, tempy;
r.x = p2x - p1x;
r.y = p2y - p1y;
assert ((r.x * r.x + r.y * r.y) > 0f);
r.normalize();
rx = r.x;
ry = r.y;
// v is perpendicular to the segment.
vx = -1f * ry;
vy = 1f * rx;
absVx = MathUtils.abs(vx);
absVy = MathUtils.abs(vy);
// Separating axis for segment (Gino, p80).
// |dot(v, p1 - c)| > dot(|v|, h)
float maxFraction = input.maxFraction;
// Build a bounding box for the segment.
final AABB segAABB = aabb;
// Vec2 t = p1 + maxFraction * (p2 - p1);
// before inline
// temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1);
// Vec2.minToOut(p1, temp, segAABB.lowerBound);
// Vec2.maxToOut(p1, temp, segAABB.upperBound);
tempx = (p2x - p1x) * maxFraction + p1x;
tempy = (p2y - p1y) * maxFraction + p1y;
segAABB.lowerBound.x = p1x < tempx ? p1x : tempx;
segAABB.lowerBound.y = p1y < tempy ? p1y : tempy;
segAABB.upperBound.x = p1x > tempx ? p1x : tempx;
segAABB.upperBound.y = p1y > tempy ? p1y : tempy;
// end inline
nodeStackIndex = 0;
nodeStack[nodeStackIndex++] = m_root;
while (nodeStackIndex > 0) {
int node = nodeStack[--nodeStackIndex] = m_root;
if (node == NULL_NODE) {
continue;
}
final AABB nodeAABB = m_aabb[node];
if (!AABB.testOverlap(nodeAABB, segAABB)) {
continue;
}
// Separating axis for segment (Gino, p80).
// |dot(v, p1 - c)| > dot(|v|, h)
// node.aabb.getCenterToOut(c);
// node.aabb.getExtentsToOut(h);
cx = (nodeAABB.lowerBound.x + nodeAABB.upperBound.x) * .5f;
cy = (nodeAABB.lowerBound.y + nodeAABB.upperBound.y) * .5f;
hx = (nodeAABB.upperBound.x - nodeAABB.lowerBound.x) * .5f;
hy = (nodeAABB.upperBound.y - nodeAABB.lowerBound.y) * .5f;
tempx = p1x - cx;
tempy = p1y - cy;
float separation = MathUtils.abs(vx * tempx + vy * tempy) - (absVx * hx + absVy * hy);
if (separation > 0.0f) {
continue;
}
int child1 = m_child1[node];
if (child1 == NULL_NODE) {
subInput.p1.x = p1x;
subInput.p1.y = p1y;
subInput.p2.x = p2x;
subInput.p2.y = p2y;
subInput.maxFraction = maxFraction;
float value = callback.raycastCallback(subInput, node);
if (value == 0.0f) {
// The client has terminated the ray cast.
return;
}
if (value > 0.0f) {
// Update segment bounding box.
maxFraction = value;
// temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1);
// Vec2.minToOut(p1, temp, segAABB.lowerBound);
// Vec2.maxToOut(p1, temp, segAABB.upperBound);
tempx = (p2x - p1x) * maxFraction + p1x;
tempy = (p2y - p1y) * maxFraction + p1y;
segAABB.lowerBound.x = p1x < tempx ? p1x : tempx;
segAABB.lowerBound.y = p1y < tempy ? p1y : tempy;
segAABB.upperBound.x = p1x > tempx ? p1x : tempx;
segAABB.upperBound.y = p1y > tempy ? p1y : tempy;
}
} else {
nodeStack[nodeStackIndex++] = child1;
nodeStack[nodeStackIndex++] = m_child2[node];
}
}
}
@Override
public final int computeHeight () {
return computeHeight(m_root);
}
private final int computeHeight (int node) {
assert (0 <= node && node < m_nodeCapacity);
if (m_child1[node] == NULL_NODE) {
return 0;
}
int height1 = computeHeight(m_child1[node]);
int height2 = computeHeight(m_child2[node]);
return 1 + MathUtils.max(height1, height2);
}
/** Validate this tree. For testing. */
public void validate () {
validateStructure(m_root);
validateMetrics(m_root);
int freeCount = 0;
int freeNode = m_freeList;
while (freeNode != NULL_NODE) {
assert (0 <= freeNode && freeNode < m_nodeCapacity);
freeNode = m_parent[freeNode];
++freeCount;
}
assert (getHeight() == computeHeight());
assert (m_nodeCount + freeCount == m_nodeCapacity);
}
@Override
public int getHeight () {
if (m_root == NULL_NODE) {
return 0;
}
return m_height[m_root];
}
@Override
public int getMaxBalance () {
int maxBalance = 0;
for (int i = 0; i < m_nodeCapacity; ++i) {
if (m_height[i] <= 1) {
continue;
}
assert (m_child1[i] != NULL_NODE);
int child1 = m_child1[i];
int child2 = m_child2[i];
int balance = MathUtils.abs(m_height[child2] - m_height[child1]);
maxBalance = MathUtils.max(maxBalance, balance);
}
return maxBalance;
}
@Override
public float getAreaRatio () {
if (m_root == NULL_NODE) {
return 0.0f;
}
final int root = m_root;
float rootArea = m_aabb[root].getPerimeter();
float totalArea = 0.0f;
for (int i = 0; i < m_nodeCapacity; ++i) {
if (m_height[i] < 0) {
// Free node in pool
continue;
}
totalArea += m_aabb[i].getPerimeter();
}
return totalArea / rootArea;
}
// /**
// * Build an optimal tree. Very expensive. For testing.
// */
// public void rebuildBottomUp() {
// int[] nodes = new int[m_nodeCount];
// int count = 0;
//
// // Build array of leaves. Free the rest.
// for (int i = 0; i < m_nodeCapacity; ++i) {
// if (m_nodes[i].height < 0) {
// // free node in pool
// continue;
// }
//
// DynamicTreeNode node = m_nodes[i];
// if (node.isLeaf()) {
// node.parent = null;
// nodes[count] = i;
// ++count;
// } else {
// freeNode(node);
// }
// }
//
// AABB b = new AABB();
// while (count > 1) {
// float minCost = Float.MAX_VALUE;
// int iMin = -1, jMin = -1;
// for (int i = 0; i < count; ++i) {
// AABB aabbi = m_nodes[nodes[i]].aabb;
//
// for (int j = i + 1; j < count; ++j) {
// AABB aabbj = m_nodes[nodes[j]].aabb;
// b.combine(aabbi, aabbj);
// float cost = b.getPerimeter();
// if (cost < minCost) {
// iMin = i;
// jMin = j;
// minCost = cost;
// }
// }
// }
//
// int index1 = nodes[iMin];
// int index2 = nodes[jMin];
// DynamicTreeNode child1 = m_nodes[index1];
// DynamicTreeNode child2 = m_nodes[index2];
//
// DynamicTreeNode parent = allocateNode();
// parent.child1 = child1;
// parent.child2 = child2;
// parent.height = 1 + MathUtils.max(child1.height, child2.height);
// parent.aabb.combine(child1.aabb, child2.aabb);
// parent.parent = null;
//
// child1.parent = parent;
// child2.parent = parent;
//
// nodes[jMin] = nodes[count - 1];
// nodes[iMin] = parent.id;
// --count;
// }
//
// m_root = m_nodes[nodes[0]];
//
// validate();
// }
private final int allocateNode () {
if (m_freeList == NULL_NODE) {
assert (m_nodeCount == m_nodeCapacity);
m_nodeCapacity *= 2;
expandBuffers(m_nodeCount, m_nodeCapacity);
}
assert (m_freeList != NULL_NODE);
int node = m_freeList;
m_freeList = m_parent[node];
m_parent[node] = NULL_NODE;
m_child1[node] = NULL_NODE;
m_height[node] = 0;
++m_nodeCount;
return node;
}
/** returns a node to the pool */
private final void freeNode (int node) {
assert (node != NULL_NODE);
assert (0 < m_nodeCount);
m_parent[node] = m_freeList != NULL_NODE ? m_freeList : NULL_NODE;
m_height[node] = -1;
m_freeList = node;
m_nodeCount--;
}
private final AABB combinedAABB = new AABB();
private final void insertLeaf (int leaf) {
if (m_root == NULL_NODE) {
m_root = leaf;
m_parent[m_root] = NULL_NODE;
return;
}
// find the best sibling
AABB leafAABB = m_aabb[leaf];
int index = m_root;
while (m_child1[index] != NULL_NODE) {
final int node = index;
int child1 = m_child1[node];
int child2 = m_child2[node];
final AABB nodeAABB = m_aabb[node];
float area = nodeAABB.getPerimeter();
combinedAABB.combine(nodeAABB, leafAABB);
float combinedArea = combinedAABB.getPerimeter();
// Cost of creating a new parent for this node and the new leaf
float cost = 2.0f * combinedArea;
// Minimum cost of pushing the leaf further down the tree
float inheritanceCost = 2.0f * (combinedArea - area);
// Cost of descending into child1
float cost1;
AABB child1AABB = m_aabb[child1];
if (m_child1[child1] == NULL_NODE) {
combinedAABB.combine(leafAABB, child1AABB);
cost1 = combinedAABB.getPerimeter() + inheritanceCost;
} else {
combinedAABB.combine(leafAABB, child1AABB);
float oldArea = child1AABB.getPerimeter();
float newArea = combinedAABB.getPerimeter();
cost1 = (newArea - oldArea) + inheritanceCost;
}
// Cost of descending into child2
float cost2;
AABB child2AABB = m_aabb[child2];
if (m_child1[child2] == NULL_NODE) {
combinedAABB.combine(leafAABB, child2AABB);
cost2 = combinedAABB.getPerimeter() + inheritanceCost;
} else {
combinedAABB.combine(leafAABB, child2AABB);
float oldArea = child2AABB.getPerimeter();
float newArea = combinedAABB.getPerimeter();
cost2 = newArea - oldArea + inheritanceCost;
}
// Descend according to the minimum cost.
if (cost < cost1 && cost < cost2) {
break;
}
// Descend
if (cost1 < cost2) {
index = child1;
} else {
index = child2;
}
}
int sibling = index;
int oldParent = m_parent[sibling];
final int newParent = allocateNode();
m_parent[newParent] = oldParent;
m_userData[newParent] = null;
m_aabb[newParent].combine(leafAABB, m_aabb[sibling]);
m_height[newParent] = m_height[sibling] + 1;
if (oldParent != NULL_NODE) {
// The sibling was not the root.
if (m_child1[oldParent] == sibling) {
m_child1[oldParent] = newParent;
} else {
m_child2[oldParent] = newParent;
}
m_child1[newParent] = sibling;
m_child2[newParent] = leaf;
m_parent[sibling] = newParent;
m_parent[leaf] = newParent;
} else {
// The sibling was the root.
m_child1[newParent] = sibling;
m_child2[newParent] = leaf;
m_parent[sibling] = newParent;
m_parent[leaf] = newParent;
m_root = newParent;
}
// Walk back up the tree fixing heights and AABBs
index = m_parent[leaf];
while (index != NULL_NODE) {
index = balance(index);
int child1 = m_child1[index];
int child2 = m_child2[index];
assert (child1 != NULL_NODE);
assert (child2 != NULL_NODE);
m_height[index] = 1 + MathUtils.max(m_height[child1], m_height[child2]);
m_aabb[index].combine(m_aabb[child1], m_aabb[child2]);
index = m_parent[index];
}
// validate();
}
private final void removeLeaf (int leaf) {
if (leaf == m_root) {
m_root = NULL_NODE;
return;
}
int parent = m_parent[leaf];
int grandParent = m_parent[parent];
int parentChild1 = m_child1[parent];
int parentChild2 = m_child2[parent];
int sibling;
if (parentChild1 == leaf) {
sibling = parentChild2;
} else {
sibling = parentChild1;
}
if (grandParent != NULL_NODE) {
// Destroy parent and connect sibling to grandParent.
if (m_child1[grandParent] == parent) {
m_child1[grandParent] = sibling;
} else {
m_child2[grandParent] = sibling;
}
m_parent[sibling] = grandParent;
freeNode(parent);
// Adjust ancestor bounds.
int index = grandParent;
while (index != NULL_NODE) {
index = balance(index);
int child1 = m_child1[index];
int child2 = m_child2[index];
m_aabb[index].combine(m_aabb[child1], m_aabb[child2]);
m_height[index] = 1 + MathUtils.max(m_height[child1], m_height[child2]);
index = m_parent[index];
}
} else {
m_root = sibling;
m_parent[sibling] = NULL_NODE;
freeNode(parent);
}
// validate();
}
// Perform a left or right rotation if node A is imbalanced.
// Returns the new root index.
private int balance (int iA) {
assert (iA != NULL_NODE);
int A = iA;
if (m_child1[A] == NULL_NODE || m_height[A] < 2) {
return iA;
}
int iB = m_child1[A];
int iC = m_child2[A];
assert (0 <= iB && iB < m_nodeCapacity);
assert (0 <= iC && iC < m_nodeCapacity);
int B = iB;
int C = iC;
int balance = m_height[C] - m_height[B];
// Rotate C up
if (balance > 1) {
int iF = m_child1[C];
int iG = m_child2[C];
int F = iF;
int G = iG;
// assert (F != null);
// assert (G != null);
assert (0 <= iF && iF < m_nodeCapacity);
assert (0 <= iG && iG < m_nodeCapacity);
// Swap A and C
m_child1[C] = iA;
int cParent = m_parent[C] = m_parent[A];
m_parent[A] = iC;
// A's old parent should point to C
if (cParent != NULL_NODE) {
if (m_child1[cParent] == iA) {
m_child1[cParent] = iC;
} else {
assert (m_child2[cParent] == iA);
m_child2[cParent] = iC;
}
} else {
m_root = iC;
}
// Rotate
if (m_height[F] > m_height[G]) {
m_child2[C] = iF;
m_child2[A] = iG;
m_parent[G] = iA;
m_aabb[A].combine(m_aabb[B], m_aabb[G]);
m_aabb[C].combine(m_aabb[A], m_aabb[F]);
m_height[A] = 1 + MathUtils.max(m_height[B], m_height[G]);
m_height[C] = 1 + MathUtils.max(m_height[A], m_height[F]);
} else {
m_child2[C] = iG;
m_child2[A] = iF;
m_parent[F] = iA;
m_aabb[A].combine(m_aabb[B], m_aabb[F]);
m_aabb[C].combine(m_aabb[A], m_aabb[G]);
m_height[A] = 1 + MathUtils.max(m_height[B], m_height[F]);
m_height[C] = 1 + MathUtils.max(m_height[A], m_height[G]);
}
return iC;
}
// Rotate B up
if (balance < -1) {
int iD = m_child1[B];
int iE = m_child2[B];
int D = iD;
int E = iE;
assert (0 <= iD && iD < m_nodeCapacity);
assert (0 <= iE && iE < m_nodeCapacity);
// Swap A and B
m_child1[B] = iA;
int Bparent = m_parent[B] = m_parent[A];
m_parent[A] = iB;
// A's old parent should point to B
if (Bparent != NULL_NODE) {
if (m_child1[Bparent] == iA) {
m_child1[Bparent] = iB;
} else {
assert (m_child2[Bparent] == iA);
m_child2[Bparent] = iB;
}
} else {
m_root = iB;
}
// Rotate
if (m_height[D] > m_height[E]) {
m_child2[B] = iD;
m_child1[A] = iE;
m_parent[E] = iA;
m_aabb[A].combine(m_aabb[C], m_aabb[E]);
m_aabb[B].combine(m_aabb[A], m_aabb[D]);
m_height[A] = 1 + MathUtils.max(m_height[C], m_height[E]);
m_height[B] = 1 + MathUtils.max(m_height[A], m_height[D]);
} else {
m_child2[B] = iE;
m_child1[A] = iD;
m_parent[D] = iA;
m_aabb[A].combine(m_aabb[C], m_aabb[D]);
m_aabb[B].combine(m_aabb[A], m_aabb[E]);
m_height[A] = 1 + MathUtils.max(m_height[C], m_height[D]);
m_height[B] = 1 + MathUtils.max(m_height[A], m_height[E]);
}
return iB;
}
return iA;
}
private void validateStructure (int node) {
if (node == NULL_NODE) {
return;
}
if (node == m_root) {
assert (m_parent[node] == NULL_NODE);
}
int child1 = m_child1[node];
int child2 = m_child2[node];
if (child1 == NULL_NODE) {
assert (child1 == NULL_NODE);
assert (child2 == NULL_NODE);
assert (m_height[node] == 0);
return;
}
assert (child1 != NULL_NODE && 0 <= child1 && child1 < m_nodeCapacity);
assert (child2 != NULL_NODE && 0 <= child2 && child2 < m_nodeCapacity);
assert (m_parent[child1] == node);
assert (m_parent[child2] == node);
validateStructure(child1);
validateStructure(child2);
}
private void validateMetrics (int node) {
if (node == NULL_NODE) {
return;
}
int child1 = m_child1[node];
int child2 = m_child2[node];
if (child1 == NULL_NODE) {
assert (child1 == NULL_NODE);
assert (child2 == NULL_NODE);
assert (m_height[node] == 0);
return;
}
assert (child1 != NULL_NODE && 0 <= child1 && child1 < m_nodeCapacity);
assert (child2 != child1 && 0 <= child2 && child2 < m_nodeCapacity);
int height1 = m_height[child1];
int height2 = m_height[child2];
int height;
height = 1 + MathUtils.max(height1, height2);
assert (m_height[node] == height);
AABB aabb = new AABB();
aabb.combine(m_aabb[child1], m_aabb[child2]);
assert (aabb.lowerBound.equals(m_aabb[node].lowerBound));
assert (aabb.upperBound.equals(m_aabb[node].upperBound));
validateMetrics(child1);
validateMetrics(child2);
}
@Override
public void drawTree (DebugDraw argDraw) {
if (m_root == NULL_NODE) {
return;
}
int height = computeHeight();
drawTree(argDraw, m_root, 0, height);
}
private final Color3f color = new Color3f();
private final Vec2 textVec = new Vec2();
public void drawTree (DebugDraw argDraw, int node, int spot, int height) {
AABB a = m_aabb[node];
a.getVertices(drawVecs);
color.set(1, (height - spot) * 1f / height, (height - spot) * 1f / height);
argDraw.drawPolygon(drawVecs, 4, color);
argDraw.getViewportTranform().getWorldToScreen(a.upperBound, textVec);
argDraw.drawString(textVec.x, textVec.y, node + "-" + (spot + 1) + "/" + height, color);
int c1 = m_child1[node];
int c2 = m_child2[node];
if (c1 != NULL_NODE) {
drawTree(argDraw, c1, spot + 1, height);
}
if (c2 != NULL_NODE) {
drawTree(argDraw, c2, spot + 1, height);
}
}
}
| /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.collision.broadphase;
import org.jbox2d.callbacks.DebugDraw;
import org.jbox2d.callbacks.TreeCallback;
import org.jbox2d.callbacks.TreeRayCastCallback;
import org.jbox2d.collision.AABB;
import org.jbox2d.collision.RayCastInput;
import org.jbox2d.common.BufferUtils;
import org.jbox2d.common.Color3f;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Vec2;
public class DynamicTreeFlatNodes implements BroadPhaseStrategy {
public static final int MAX_STACK_SIZE = 64;
public static final int NULL_NODE = -1;
public static final int INITIAL_BUFFER_LENGTH = 16;
public int m_root;
public AABB[] m_aabb;
public Object[] m_userData;
protected int[] m_parent;
protected int[] m_child1;
protected int[] m_child2;
protected int[] m_height;
private int m_nodeCount;
private int m_nodeCapacity;
private int m_freeList;
private final Vec2[] drawVecs = new Vec2[4];
public DynamicTreeFlatNodes () {
m_root = NULL_NODE;
m_nodeCount = 0;
m_nodeCapacity = 16;
expandBuffers(0, m_nodeCapacity);
for (int i = 0; i < drawVecs.length; i++) {
drawVecs[i] = new Vec2();
}
}
private void expandBuffers (int oldSize, int newSize) {
m_aabb = BufferUtils.reallocateBuffer(AABB.class, m_aabb, oldSize, newSize);
m_userData = BufferUtils.reallocateBuffer(Object.class, m_userData, oldSize, newSize);
m_parent = BufferUtils.reallocateBuffer(m_parent, oldSize, newSize);
m_child1 = BufferUtils.reallocateBuffer(m_child1, oldSize, newSize);
m_child2 = BufferUtils.reallocateBuffer(m_child2, oldSize, newSize);
m_height = BufferUtils.reallocateBuffer(m_height, oldSize, newSize);
// Build a linked list for the free list.
for (int i = oldSize; i < newSize; i++) {
m_aabb[i] = new AABB();
m_parent[i] = (i == newSize - 1) ? NULL_NODE : i + 1;
m_height[i] = -1;
m_child1[i] = -1;
m_child2[i] = -1;
}
m_freeList = oldSize;
}
@Override
public final int createProxy (final AABB aabb, Object userData) {
final int node = allocateNode();
// Fatten the aabb
final AABB nodeAABB = m_aabb[node];
nodeAABB.lowerBound.x = aabb.lowerBound.x - Settings.aabbExtension;
nodeAABB.lowerBound.y = aabb.lowerBound.y - Settings.aabbExtension;
nodeAABB.upperBound.x = aabb.upperBound.x + Settings.aabbExtension;
nodeAABB.upperBound.y = aabb.upperBound.y + Settings.aabbExtension;
m_userData[node] = userData;
insertLeaf(node);
return node;
}
@Override
public final void destroyProxy (int proxyId) {
assert (0 <= proxyId && proxyId < m_nodeCapacity);
assert (m_child1[proxyId] == NULL_NODE);
removeLeaf(proxyId);
freeNode(proxyId);
}
@Override
public final boolean moveProxy (int proxyId, final AABB aabb, Vec2 displacement) {
assert (0 <= proxyId && proxyId < m_nodeCapacity);
final int node = proxyId;
assert (m_child1[node] == NULL_NODE);
final AABB nodeAABB = m_aabb[node];
// if (nodeAABB.contains(aabb)) {
if (nodeAABB.lowerBound.x <= aabb.lowerBound.x && nodeAABB.lowerBound.y <= aabb.lowerBound.y
&& aabb.upperBound.x <= nodeAABB.upperBound.x && aabb.upperBound.y <= nodeAABB.upperBound.y) {
return false;
}
removeLeaf(node);
// Extend AABB
final Vec2 lowerBound = nodeAABB.lowerBound;
final Vec2 upperBound = nodeAABB.upperBound;
lowerBound.x = aabb.lowerBound.x - Settings.aabbExtension;
lowerBound.y = aabb.lowerBound.y - Settings.aabbExtension;
upperBound.x = aabb.upperBound.x + Settings.aabbExtension;
upperBound.y = aabb.upperBound.y + Settings.aabbExtension;
// Predict AABB displacement.
final float dx = displacement.x * Settings.aabbMultiplier;
final float dy = displacement.y * Settings.aabbMultiplier;
if (dx < 0.0f) {
lowerBound.x += dx;
} else {
upperBound.x += dx;
}
if (dy < 0.0f) {
lowerBound.y += dy;
} else {
upperBound.y += dy;
}
insertLeaf(proxyId);
return true;
}
@Override
public final Object getUserData (int proxyId) {
assert (0 <= proxyId && proxyId < m_nodeCount);
return m_userData[proxyId];
}
@Override
public final AABB getFatAABB (int proxyId) {
assert (0 <= proxyId && proxyId < m_nodeCount);
return m_aabb[proxyId];
}
private int[] nodeStack = new int[20];
private int nodeStackIndex;
@Override
public final void query (TreeCallback callback, AABB aabb) {
nodeStackIndex = 0;
nodeStack[nodeStackIndex++] = m_root;
while (nodeStackIndex > 0) {
int node = nodeStack[--nodeStackIndex];
if (node == NULL_NODE) {
continue;
}
if (AABB.testOverlap(m_aabb[node], aabb)) {
int child1 = m_child1[node];
if (child1 == NULL_NODE) {
boolean proceed = callback.treeCallback(node);
if (!proceed) {
return;
}
} else {
if (nodeStack.length - nodeStackIndex - 2 <= 0) {
nodeStack = BufferUtils.reallocateBuffer(nodeStack, nodeStack.length, nodeStack.length * 2);
}
nodeStack[nodeStackIndex++] = child1;
nodeStack[nodeStackIndex++] = m_child2[node];
}
}
}
}
private final Vec2 r = new Vec2();
private final AABB aabb = new AABB();
private final RayCastInput subInput = new RayCastInput();
@Override
public void raycast (TreeRayCastCallback callback, RayCastInput input) {
final Vec2 p1 = input.p1;
final Vec2 p2 = input.p2;
float p1x = p1.x, p2x = p2.x, p1y = p1.y, p2y = p2.y;
float vx, vy;
float rx, ry;
float absVx, absVy;
float cx, cy;
float hx, hy;
float tempx, tempy;
r.x = p2x - p1x;
r.y = p2y - p1y;
assert ((r.x * r.x + r.y * r.y) > 0f);
r.normalize();
rx = r.x;
ry = r.y;
// v is perpendicular to the segment.
vx = -1f * ry;
vy = 1f * rx;
absVx = MathUtils.abs(vx);
absVy = MathUtils.abs(vy);
// Separating axis for segment (Gino, p80).
// |dot(v, p1 - c)| > dot(|v|, h)
float maxFraction = input.maxFraction;
// Build a bounding box for the segment.
final AABB segAABB = aabb;
// Vec2 t = p1 + maxFraction * (p2 - p1);
// before inline
// temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1);
// Vec2.minToOut(p1, temp, segAABB.lowerBound);
// Vec2.maxToOut(p1, temp, segAABB.upperBound);
tempx = (p2x - p1x) * maxFraction + p1x;
tempy = (p2y - p1y) * maxFraction + p1y;
segAABB.lowerBound.x = p1x < tempx ? p1x : tempx;
segAABB.lowerBound.y = p1y < tempy ? p1y : tempy;
segAABB.upperBound.x = p1x > tempx ? p1x : tempx;
segAABB.upperBound.y = p1y > tempy ? p1y : tempy;
// end inline
nodeStackIndex = 0;
nodeStack[nodeStackIndex++] = m_root;
while (nodeStackIndex > 0) {
int node = nodeStack[--nodeStackIndex] = m_root;
if (node == NULL_NODE) {
continue;
}
final AABB nodeAABB = m_aabb[node];
if (!AABB.testOverlap(nodeAABB, segAABB)) {
continue;
}
// Separating axis for segment (Gino, p80).
// |dot(v, p1 - c)| > dot(|v|, h)
// node.aabb.getCenterToOut(c);
// node.aabb.getExtentsToOut(h);
cx = (nodeAABB.lowerBound.x + nodeAABB.upperBound.x) * .5f;
cy = (nodeAABB.lowerBound.y + nodeAABB.upperBound.y) * .5f;
hx = (nodeAABB.upperBound.x - nodeAABB.lowerBound.x) * .5f;
hy = (nodeAABB.upperBound.y - nodeAABB.lowerBound.y) * .5f;
tempx = p1x - cx;
tempy = p1y - cy;
float separation = MathUtils.abs(vx * tempx + vy * tempy) - (absVx * hx + absVy * hy);
if (separation > 0.0f) {
continue;
}
int child1 = m_child1[node];
if (child1 == NULL_NODE) {
subInput.p1.x = p1x;
subInput.p1.y = p1y;
subInput.p2.x = p2x;
subInput.p2.y = p2y;
subInput.maxFraction = maxFraction;
float value = callback.raycastCallback(subInput, node);
if (value == 0.0f) {
// The client has terminated the ray cast.
return;
}
if (value > 0.0f) {
// Update segment bounding box.
maxFraction = value;
// temp.set(p2).subLocal(p1).mulLocal(maxFraction).addLocal(p1);
// Vec2.minToOut(p1, temp, segAABB.lowerBound);
// Vec2.maxToOut(p1, temp, segAABB.upperBound);
tempx = (p2x - p1x) * maxFraction + p1x;
tempy = (p2y - p1y) * maxFraction + p1y;
segAABB.lowerBound.x = p1x < tempx ? p1x : tempx;
segAABB.lowerBound.y = p1y < tempy ? p1y : tempy;
segAABB.upperBound.x = p1x > tempx ? p1x : tempx;
segAABB.upperBound.y = p1y > tempy ? p1y : tempy;
}
} else {
nodeStack[nodeStackIndex++] = child1;
nodeStack[nodeStackIndex++] = m_child2[node];
}
}
}
@Override
public final int computeHeight () {
return computeHeight(m_root);
}
private final int computeHeight (int node) {
assert (0 <= node && node < m_nodeCapacity);
if (m_child1[node] == NULL_NODE) {
return 0;
}
int height1 = computeHeight(m_child1[node]);
int height2 = computeHeight(m_child2[node]);
return 1 + MathUtils.max(height1, height2);
}
/** Validate this tree. For testing. */
public void validate () {
validateStructure(m_root);
validateMetrics(m_root);
int freeCount = 0;
int freeNode = m_freeList;
while (freeNode != NULL_NODE) {
assert (0 <= freeNode && freeNode < m_nodeCapacity);
freeNode = m_parent[freeNode];
++freeCount;
}
assert (getHeight() == computeHeight());
assert (m_nodeCount + freeCount == m_nodeCapacity);
}
@Override
public int getHeight () {
if (m_root == NULL_NODE) {
return 0;
}
return m_height[m_root];
}
@Override
public int getMaxBalance () {
int maxBalance = 0;
for (int i = 0; i < m_nodeCapacity; ++i) {
if (m_height[i] <= 1) {
continue;
}
assert (m_child1[i] != NULL_NODE);
int child1 = m_child1[i];
int child2 = m_child2[i];
int balance = MathUtils.abs(m_height[child2] - m_height[child1]);
maxBalance = MathUtils.max(maxBalance, balance);
}
return maxBalance;
}
@Override
public float getAreaRatio () {
if (m_root == NULL_NODE) {
return 0.0f;
}
final int root = m_root;
float rootArea = m_aabb[root].getPerimeter();
float totalArea = 0.0f;
for (int i = 0; i < m_nodeCapacity; ++i) {
if (m_height[i] < 0) {
// Free node in pool
continue;
}
totalArea += m_aabb[i].getPerimeter();
}
return totalArea / rootArea;
}
// /**
// * Build an optimal tree. Very expensive. For testing.
// */
// public void rebuildBottomUp() {
// int[] nodes = new int[m_nodeCount];
// int count = 0;
//
// // Build array of leaves. Free the rest.
// for (int i = 0; i < m_nodeCapacity; ++i) {
// if (m_nodes[i].height < 0) {
// // free node in pool
// continue;
// }
//
// DynamicTreeNode node = m_nodes[i];
// if (node.isLeaf()) {
// node.parent = null;
// nodes[count] = i;
// ++count;
// } else {
// freeNode(node);
// }
// }
//
// AABB b = new AABB();
// while (count > 1) {
// float minCost = Float.MAX_VALUE;
// int iMin = -1, jMin = -1;
// for (int i = 0; i < count; ++i) {
// AABB aabbi = m_nodes[nodes[i]].aabb;
//
// for (int j = i + 1; j < count; ++j) {
// AABB aabbj = m_nodes[nodes[j]].aabb;
// b.combine(aabbi, aabbj);
// float cost = b.getPerimeter();
// if (cost < minCost) {
// iMin = i;
// jMin = j;
// minCost = cost;
// }
// }
// }
//
// int index1 = nodes[iMin];
// int index2 = nodes[jMin];
// DynamicTreeNode child1 = m_nodes[index1];
// DynamicTreeNode child2 = m_nodes[index2];
//
// DynamicTreeNode parent = allocateNode();
// parent.child1 = child1;
// parent.child2 = child2;
// parent.height = 1 + MathUtils.max(child1.height, child2.height);
// parent.aabb.combine(child1.aabb, child2.aabb);
// parent.parent = null;
//
// child1.parent = parent;
// child2.parent = parent;
//
// nodes[jMin] = nodes[count - 1];
// nodes[iMin] = parent.id;
// --count;
// }
//
// m_root = m_nodes[nodes[0]];
//
// validate();
// }
private final int allocateNode () {
if (m_freeList == NULL_NODE) {
assert (m_nodeCount == m_nodeCapacity);
m_nodeCapacity *= 2;
expandBuffers(m_nodeCount, m_nodeCapacity);
}
assert (m_freeList != NULL_NODE);
int node = m_freeList;
m_freeList = m_parent[node];
m_parent[node] = NULL_NODE;
m_child1[node] = NULL_NODE;
m_height[node] = 0;
++m_nodeCount;
return node;
}
/** returns a node to the pool */
private final void freeNode (int node) {
assert (node != NULL_NODE);
assert (0 < m_nodeCount);
m_parent[node] = m_freeList != NULL_NODE ? m_freeList : NULL_NODE;
m_height[node] = -1;
m_freeList = node;
m_nodeCount--;
}
private final AABB combinedAABB = new AABB();
private final void insertLeaf (int leaf) {
if (m_root == NULL_NODE) {
m_root = leaf;
m_parent[m_root] = NULL_NODE;
return;
}
// find the best sibling
AABB leafAABB = m_aabb[leaf];
int index = m_root;
while (m_child1[index] != NULL_NODE) {
final int node = index;
int child1 = m_child1[node];
int child2 = m_child2[node];
final AABB nodeAABB = m_aabb[node];
float area = nodeAABB.getPerimeter();
combinedAABB.combine(nodeAABB, leafAABB);
float combinedArea = combinedAABB.getPerimeter();
// Cost of creating a new parent for this node and the new leaf
float cost = 2.0f * combinedArea;
// Minimum cost of pushing the leaf further down the tree
float inheritanceCost = 2.0f * (combinedArea - area);
// Cost of descending into child1
float cost1;
AABB child1AABB = m_aabb[child1];
if (m_child1[child1] == NULL_NODE) {
combinedAABB.combine(leafAABB, child1AABB);
cost1 = combinedAABB.getPerimeter() + inheritanceCost;
} else {
combinedAABB.combine(leafAABB, child1AABB);
float oldArea = child1AABB.getPerimeter();
float newArea = combinedAABB.getPerimeter();
cost1 = (newArea - oldArea) + inheritanceCost;
}
// Cost of descending into child2
float cost2;
AABB child2AABB = m_aabb[child2];
if (m_child1[child2] == NULL_NODE) {
combinedAABB.combine(leafAABB, child2AABB);
cost2 = combinedAABB.getPerimeter() + inheritanceCost;
} else {
combinedAABB.combine(leafAABB, child2AABB);
float oldArea = child2AABB.getPerimeter();
float newArea = combinedAABB.getPerimeter();
cost2 = newArea - oldArea + inheritanceCost;
}
// Descend according to the minimum cost.
if (cost < cost1 && cost < cost2) {
break;
}
// Descend
if (cost1 < cost2) {
index = child1;
} else {
index = child2;
}
}
int sibling = index;
int oldParent = m_parent[sibling];
final int newParent = allocateNode();
m_parent[newParent] = oldParent;
m_userData[newParent] = null;
m_aabb[newParent].combine(leafAABB, m_aabb[sibling]);
m_height[newParent] = m_height[sibling] + 1;
if (oldParent != NULL_NODE) {
// The sibling was not the root.
if (m_child1[oldParent] == sibling) {
m_child1[oldParent] = newParent;
} else {
m_child2[oldParent] = newParent;
}
m_child1[newParent] = sibling;
m_child2[newParent] = leaf;
m_parent[sibling] = newParent;
m_parent[leaf] = newParent;
} else {
// The sibling was the root.
m_child1[newParent] = sibling;
m_child2[newParent] = leaf;
m_parent[sibling] = newParent;
m_parent[leaf] = newParent;
m_root = newParent;
}
// Walk back up the tree fixing heights and AABBs
index = m_parent[leaf];
while (index != NULL_NODE) {
index = balance(index);
int child1 = m_child1[index];
int child2 = m_child2[index];
assert (child1 != NULL_NODE);
assert (child2 != NULL_NODE);
m_height[index] = 1 + MathUtils.max(m_height[child1], m_height[child2]);
m_aabb[index].combine(m_aabb[child1], m_aabb[child2]);
index = m_parent[index];
}
// validate();
}
private final void removeLeaf (int leaf) {
if (leaf == m_root) {
m_root = NULL_NODE;
return;
}
int parent = m_parent[leaf];
int grandParent = m_parent[parent];
int parentChild1 = m_child1[parent];
int parentChild2 = m_child2[parent];
int sibling;
if (parentChild1 == leaf) {
sibling = parentChild2;
} else {
sibling = parentChild1;
}
if (grandParent != NULL_NODE) {
// Destroy parent and connect sibling to grandParent.
if (m_child1[grandParent] == parent) {
m_child1[grandParent] = sibling;
} else {
m_child2[grandParent] = sibling;
}
m_parent[sibling] = grandParent;
freeNode(parent);
// Adjust ancestor bounds.
int index = grandParent;
while (index != NULL_NODE) {
index = balance(index);
int child1 = m_child1[index];
int child2 = m_child2[index];
m_aabb[index].combine(m_aabb[child1], m_aabb[child2]);
m_height[index] = 1 + MathUtils.max(m_height[child1], m_height[child2]);
index = m_parent[index];
}
} else {
m_root = sibling;
m_parent[sibling] = NULL_NODE;
freeNode(parent);
}
// validate();
}
// Perform a left or right rotation if node A is imbalanced.
// Returns the new root index.
private int balance (int iA) {
assert (iA != NULL_NODE);
int A = iA;
if (m_child1[A] == NULL_NODE || m_height[A] < 2) {
return iA;
}
int iB = m_child1[A];
int iC = m_child2[A];
assert (0 <= iB && iB < m_nodeCapacity);
assert (0 <= iC && iC < m_nodeCapacity);
int B = iB;
int C = iC;
int balance = m_height[C] - m_height[B];
// Rotate C up
if (balance > 1) {
int iF = m_child1[C];
int iG = m_child2[C];
int F = iF;
int G = iG;
// assert (F != null);
// assert (G != null);
assert (0 <= iF && iF < m_nodeCapacity);
assert (0 <= iG && iG < m_nodeCapacity);
// Swap A and C
m_child1[C] = iA;
int cParent = m_parent[C] = m_parent[A];
m_parent[A] = iC;
// A's old parent should point to C
if (cParent != NULL_NODE) {
if (m_child1[cParent] == iA) {
m_child1[cParent] = iC;
} else {
assert (m_child2[cParent] == iA);
m_child2[cParent] = iC;
}
} else {
m_root = iC;
}
// Rotate
if (m_height[F] > m_height[G]) {
m_child2[C] = iF;
m_child2[A] = iG;
m_parent[G] = iA;
m_aabb[A].combine(m_aabb[B], m_aabb[G]);
m_aabb[C].combine(m_aabb[A], m_aabb[F]);
m_height[A] = 1 + MathUtils.max(m_height[B], m_height[G]);
m_height[C] = 1 + MathUtils.max(m_height[A], m_height[F]);
} else {
m_child2[C] = iG;
m_child2[A] = iF;
m_parent[F] = iA;
m_aabb[A].combine(m_aabb[B], m_aabb[F]);
m_aabb[C].combine(m_aabb[A], m_aabb[G]);
m_height[A] = 1 + MathUtils.max(m_height[B], m_height[F]);
m_height[C] = 1 + MathUtils.max(m_height[A], m_height[G]);
}
return iC;
}
// Rotate B up
if (balance < -1) {
int iD = m_child1[B];
int iE = m_child2[B];
int D = iD;
int E = iE;
assert (0 <= iD && iD < m_nodeCapacity);
assert (0 <= iE && iE < m_nodeCapacity);
// Swap A and B
m_child1[B] = iA;
int Bparent = m_parent[B] = m_parent[A];
m_parent[A] = iB;
// A's old parent should point to B
if (Bparent != NULL_NODE) {
if (m_child1[Bparent] == iA) {
m_child1[Bparent] = iB;
} else {
assert (m_child2[Bparent] == iA);
m_child2[Bparent] = iB;
}
} else {
m_root = iB;
}
// Rotate
if (m_height[D] > m_height[E]) {
m_child2[B] = iD;
m_child1[A] = iE;
m_parent[E] = iA;
m_aabb[A].combine(m_aabb[C], m_aabb[E]);
m_aabb[B].combine(m_aabb[A], m_aabb[D]);
m_height[A] = 1 + MathUtils.max(m_height[C], m_height[E]);
m_height[B] = 1 + MathUtils.max(m_height[A], m_height[D]);
} else {
m_child2[B] = iE;
m_child1[A] = iD;
m_parent[D] = iA;
m_aabb[A].combine(m_aabb[C], m_aabb[D]);
m_aabb[B].combine(m_aabb[A], m_aabb[E]);
m_height[A] = 1 + MathUtils.max(m_height[C], m_height[D]);
m_height[B] = 1 + MathUtils.max(m_height[A], m_height[E]);
}
return iB;
}
return iA;
}
private void validateStructure (int node) {
if (node == NULL_NODE) {
return;
}
if (node == m_root) {
assert (m_parent[node] == NULL_NODE);
}
int child1 = m_child1[node];
int child2 = m_child2[node];
if (child1 == NULL_NODE) {
assert (child1 == NULL_NODE);
assert (child2 == NULL_NODE);
assert (m_height[node] == 0);
return;
}
assert (child1 != NULL_NODE && 0 <= child1 && child1 < m_nodeCapacity);
assert (child2 != NULL_NODE && 0 <= child2 && child2 < m_nodeCapacity);
assert (m_parent[child1] == node);
assert (m_parent[child2] == node);
validateStructure(child1);
validateStructure(child2);
}
private void validateMetrics (int node) {
if (node == NULL_NODE) {
return;
}
int child1 = m_child1[node];
int child2 = m_child2[node];
if (child1 == NULL_NODE) {
assert (child1 == NULL_NODE);
assert (child2 == NULL_NODE);
assert (m_height[node] == 0);
return;
}
assert (child1 != NULL_NODE && 0 <= child1 && child1 < m_nodeCapacity);
assert (child2 != child1 && 0 <= child2 && child2 < m_nodeCapacity);
int height1 = m_height[child1];
int height2 = m_height[child2];
int height;
height = 1 + MathUtils.max(height1, height2);
assert (m_height[node] == height);
AABB aabb = new AABB();
aabb.combine(m_aabb[child1], m_aabb[child2]);
assert (aabb.lowerBound.equals(m_aabb[node].lowerBound));
assert (aabb.upperBound.equals(m_aabb[node].upperBound));
validateMetrics(child1);
validateMetrics(child2);
}
@Override
public void drawTree (DebugDraw argDraw) {
if (m_root == NULL_NODE) {
return;
}
int height = computeHeight();
drawTree(argDraw, m_root, 0, height);
}
private final Color3f color = new Color3f();
private final Vec2 textVec = new Vec2();
public void drawTree (DebugDraw argDraw, int node, int spot, int height) {
AABB a = m_aabb[node];
a.getVertices(drawVecs);
color.set(1, (height - spot) * 1f / height, (height - spot) * 1f / height);
argDraw.drawPolygon(drawVecs, 4, color);
argDraw.getViewportTranform().getWorldToScreen(a.upperBound, textVec);
argDraw.drawString(textVec.x, textVec.y, node + "-" + (spot + 1) + "/" + height, color);
int c1 = m_child1[node];
int c2 = m_child2[node];
if (c1 != NULL_NODE) {
drawTree(argDraw, c1, spot + 1, height);
}
if (c2 != NULL_NODE) {
drawTree(argDraw, c2, spot + 1, height);
}
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/UISimpleTest.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.ScreenUtils;
public class UISimpleTest extends GdxTest {
Skin skin;
Stage stage;
SpriteBatch batch;
@Override
public void create () {
batch = new SpriteBatch();
stage = new Stage();
Gdx.input.setInputProcessor(stage);
// A skin can be loaded via JSON or defined programmatically, either is fine. Using a skin is optional but strongly
// recommended solely for the convenience of getting a texture, region, etc as a drawable, tinted drawable, etc.
skin = new Skin();
// Generate a 1x1 white texture and store it in the skin named "white".
Pixmap pixmap = new Pixmap(1, 1, Format.RGBA8888);
pixmap.setColor(Color.WHITE);
pixmap.fill();
skin.add("white", new Texture(pixmap));
// Store the default libGDX font under the name "default".
skin.add("default", new BitmapFont());
// Configure a TextButtonStyle and name it "default". Skin resources are stored by type, so this doesn't overwrite the font.
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.newDrawable("white", Color.DARK_GRAY);
textButtonStyle.down = skin.newDrawable("white", Color.DARK_GRAY);
textButtonStyle.checked = skin.newDrawable("white", Color.BLUE);
textButtonStyle.over = skin.newDrawable("white", Color.LIGHT_GRAY);
textButtonStyle.font = skin.getFont("default");
skin.add("default", textButtonStyle);
// Create a table that fills the screen. Everything else will go inside this table.
Table table = new Table();
table.setFillParent(true);
stage.addActor(table);
// Create a button with the "default" TextButtonStyle. A 3rd parameter can be used to specify a name other than "default".
final TextButton button = new TextButton("Click me!", skin);
table.add(button);
// Add a listener to the button. ChangeListener is fired when the button's checked state changes, eg when clicked,
// Button#setChecked() is called, via a key press, etc. If the event.cancel() is called, the checked state will be reverted.
// ClickListener could have been used, but would only fire when clicked. Also, canceling a ClickListener event won't
// revert the checked state.
button.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("Clicked! Is checked: " + button.isChecked());
button.setText("Good job!");
}
});
// Add an image actor. Have to set the size, else it would be the size of the drawable (which is the 1x1 texture).
table.add(new Image(skin.newDrawable("white", Color.RED))).size(64);
}
@Override
public void render () {
ScreenUtils.clear(0.2f, 0.2f, 0.2f, 1);
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
}
@Override
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
}
@Override
public void dispose () {
stage.dispose();
skin.dispose();
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.ScreenUtils;
public class UISimpleTest extends GdxTest {
Skin skin;
Stage stage;
SpriteBatch batch;
@Override
public void create () {
batch = new SpriteBatch();
stage = new Stage();
Gdx.input.setInputProcessor(stage);
// A skin can be loaded via JSON or defined programmatically, either is fine. Using a skin is optional but strongly
// recommended solely for the convenience of getting a texture, region, etc as a drawable, tinted drawable, etc.
skin = new Skin();
// Generate a 1x1 white texture and store it in the skin named "white".
Pixmap pixmap = new Pixmap(1, 1, Format.RGBA8888);
pixmap.setColor(Color.WHITE);
pixmap.fill();
skin.add("white", new Texture(pixmap));
// Store the default libGDX font under the name "default".
skin.add("default", new BitmapFont());
// Configure a TextButtonStyle and name it "default". Skin resources are stored by type, so this doesn't overwrite the font.
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.newDrawable("white", Color.DARK_GRAY);
textButtonStyle.down = skin.newDrawable("white", Color.DARK_GRAY);
textButtonStyle.checked = skin.newDrawable("white", Color.BLUE);
textButtonStyle.over = skin.newDrawable("white", Color.LIGHT_GRAY);
textButtonStyle.font = skin.getFont("default");
skin.add("default", textButtonStyle);
// Create a table that fills the screen. Everything else will go inside this table.
Table table = new Table();
table.setFillParent(true);
stage.addActor(table);
// Create a button with the "default" TextButtonStyle. A 3rd parameter can be used to specify a name other than "default".
final TextButton button = new TextButton("Click me!", skin);
table.add(button);
// Add a listener to the button. ChangeListener is fired when the button's checked state changes, eg when clicked,
// Button#setChecked() is called, via a key press, etc. If the event.cancel() is called, the checked state will be reverted.
// ClickListener could have been used, but would only fire when clicked. Also, canceling a ClickListener event won't
// revert the checked state.
button.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("Clicked! Is checked: " + button.isChecked());
button.setText("Good job!");
}
});
// Add an image actor. Have to set the size, else it would be the size of the drawable (which is the 1x1 texture).
table.add(new Image(skin.newDrawable("white", Color.RED))).size(64);
}
@Override
public void render () {
ScreenUtils.clear(0.2f, 0.2f, 0.2f, 1);
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
}
@Override
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
}
@Override
public void dispose () {
stage.dispose();
skin.dispose();
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btConvexInternalAabbCachingShape.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btConvexInternalAabbCachingShape extends btConvexInternalShape {
private long swigCPtr;
protected btConvexInternalAabbCachingShape (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btConvexInternalAabbCachingShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexInternalAabbCachingShape, normally you should not need this constructor it's intended for low-level
* usage. */
public btConvexInternalAabbCachingShape (long cPtr, boolean cMemoryOwn) {
this("btConvexInternalAabbCachingShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btConvexInternalAabbCachingShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btConvexInternalAabbCachingShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btConvexInternalAabbCachingShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void recalcLocalAabb () {
CollisionJNI.btConvexInternalAabbCachingShape_recalcLocalAabb(swigCPtr, this);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btConvexInternalAabbCachingShape extends btConvexInternalShape {
private long swigCPtr;
protected btConvexInternalAabbCachingShape (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btConvexInternalAabbCachingShape_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btConvexInternalAabbCachingShape, normally you should not need this constructor it's intended for low-level
* usage. */
public btConvexInternalAabbCachingShape (long cPtr, boolean cMemoryOwn) {
this("btConvexInternalAabbCachingShape", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btConvexInternalAabbCachingShape_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btConvexInternalAabbCachingShape obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btConvexInternalAabbCachingShape(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void recalcLocalAabb () {
CollisionJNI.btConvexInternalAabbCachingShape_recalcLocalAabb(swigCPtr, this);
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-bullet/jni/swig-src/dynamics/com/badlogic/gdx/physics/bullet/dynamics/btGeneric6DofSpring2ConstraintDoubleData2.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btGeneric6DofSpring2ConstraintDoubleData2 extends BulletBase {
private long swigCPtr;
protected btGeneric6DofSpring2ConstraintDoubleData2 (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btGeneric6DofSpring2ConstraintDoubleData2, normally you should not need this constructor it's intended for
* low-level usage. */
public btGeneric6DofSpring2ConstraintDoubleData2 (long cPtr, boolean cMemoryOwn) {
this("btGeneric6DofSpring2ConstraintDoubleData2", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btGeneric6DofSpring2ConstraintDoubleData2 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btGeneric6DofSpring2ConstraintDoubleData2(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setTypeConstraintData (btTypedConstraintDoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_typeConstraintData_set(swigCPtr, this,
btTypedConstraintDoubleData.getCPtr(value), value);
}
public btTypedConstraintDoubleData getTypeConstraintData () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_typeConstraintData_get(swigCPtr, this);
return (cPtr == 0) ? null : new btTypedConstraintDoubleData(cPtr, false);
}
public void setRbAFrame (btTransformDoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rbAFrame_set(swigCPtr, this, btTransformDoubleData.getCPtr(value),
value);
}
public btTransformDoubleData getRbAFrame () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rbAFrame_get(swigCPtr, this);
return (cPtr == 0) ? null : new btTransformDoubleData(cPtr, false);
}
public void setRbBFrame (btTransformDoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rbBFrame_set(swigCPtr, this, btTransformDoubleData.getCPtr(value),
value);
}
public btTransformDoubleData getRbBFrame () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rbBFrame_get(swigCPtr, this);
return (cPtr == 0) ? null : new btTransformDoubleData(cPtr, false);
}
public void setLinearUpperLimit (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearUpperLimit_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearUpperLimit () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearUpperLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearLowerLimit (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearLowerLimit_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearLowerLimit () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearLowerLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearBounce (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearBounce_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearBounce () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearBounce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearStopERP (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearStopERP_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearStopERP () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearStopERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearStopCFM (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearStopCFM_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearStopCFM () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearStopCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearMotorERP (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMotorERP_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearMotorERP () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMotorERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearMotorCFM (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMotorCFM_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearMotorCFM () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMotorCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearTargetVelocity (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearTargetVelocity_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearTargetVelocity () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearTargetVelocity_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearMaxMotorForce (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMaxMotorForce_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearMaxMotorForce () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMaxMotorForce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearServoTarget (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearServoTarget_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearServoTarget () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearServoTarget_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearSpringStiffness (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringStiffness_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearSpringStiffness () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringStiffness_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearSpringDamping (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringDamping_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearSpringDamping () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringDamping_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearEquilibriumPoint (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEquilibriumPoint_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearEquilibriumPoint () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEquilibriumPoint_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearEnableMotor (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEnableMotor_set(swigCPtr, this, value);
}
public String getLinearEnableMotor () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEnableMotor_get(swigCPtr, this);
}
public void setLinearServoMotor (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearServoMotor_set(swigCPtr, this, value);
}
public String getLinearServoMotor () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearServoMotor_get(swigCPtr, this);
}
public void setLinearEnableSpring (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEnableSpring_set(swigCPtr, this, value);
}
public String getLinearEnableSpring () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEnableSpring_get(swigCPtr, this);
}
public void setLinearSpringStiffnessLimited (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringStiffnessLimited_set(swigCPtr, this, value);
}
public String getLinearSpringStiffnessLimited () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringStiffnessLimited_get(swigCPtr, this);
}
public void setLinearSpringDampingLimited (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringDampingLimited_set(swigCPtr, this, value);
}
public String getLinearSpringDampingLimited () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringDampingLimited_get(swigCPtr, this);
}
public void setPadding1 (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_padding1_set(swigCPtr, this, value);
}
public String getPadding1 () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_padding1_get(swigCPtr, this);
}
public void setAngularUpperLimit (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularUpperLimit_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularUpperLimit () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularUpperLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularLowerLimit (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularLowerLimit_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularLowerLimit () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularLowerLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularBounce (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularBounce_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getAngularBounce () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularBounce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularStopERP (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularStopERP_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getAngularStopERP () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularStopERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularStopCFM (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularStopCFM_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getAngularStopCFM () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularStopCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularMotorERP (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMotorERP_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularMotorERP () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMotorERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularMotorCFM (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMotorCFM_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularMotorCFM () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMotorCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularTargetVelocity (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularTargetVelocity_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularTargetVelocity () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularTargetVelocity_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularMaxMotorForce (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMaxMotorForce_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularMaxMotorForce () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMaxMotorForce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularServoTarget (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularServoTarget_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularServoTarget () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularServoTarget_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularSpringStiffness (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringStiffness_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularSpringStiffness () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringStiffness_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularSpringDamping (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringDamping_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularSpringDamping () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringDamping_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularEquilibriumPoint (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEquilibriumPoint_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularEquilibriumPoint () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEquilibriumPoint_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularEnableMotor (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEnableMotor_set(swigCPtr, this, value);
}
public String getAngularEnableMotor () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEnableMotor_get(swigCPtr, this);
}
public void setAngularServoMotor (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularServoMotor_set(swigCPtr, this, value);
}
public String getAngularServoMotor () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularServoMotor_get(swigCPtr, this);
}
public void setAngularEnableSpring (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEnableSpring_set(swigCPtr, this, value);
}
public String getAngularEnableSpring () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEnableSpring_get(swigCPtr, this);
}
public void setAngularSpringStiffnessLimited (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringStiffnessLimited_set(swigCPtr, this, value);
}
public String getAngularSpringStiffnessLimited () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringStiffnessLimited_get(swigCPtr, this);
}
public void setAngularSpringDampingLimited (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringDampingLimited_set(swigCPtr, this, value);
}
public String getAngularSpringDampingLimited () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringDampingLimited_get(swigCPtr, this);
}
public void setRotateOrder (int value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rotateOrder_set(swigCPtr, this, value);
}
public int getRotateOrder () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rotateOrder_get(swigCPtr, this);
}
public btGeneric6DofSpring2ConstraintDoubleData2 () {
this(DynamicsJNI.new_btGeneric6DofSpring2ConstraintDoubleData2(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btGeneric6DofSpring2ConstraintDoubleData2 extends BulletBase {
private long swigCPtr;
protected btGeneric6DofSpring2ConstraintDoubleData2 (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btGeneric6DofSpring2ConstraintDoubleData2, normally you should not need this constructor it's intended for
* low-level usage. */
public btGeneric6DofSpring2ConstraintDoubleData2 (long cPtr, boolean cMemoryOwn) {
this("btGeneric6DofSpring2ConstraintDoubleData2", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btGeneric6DofSpring2ConstraintDoubleData2 obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btGeneric6DofSpring2ConstraintDoubleData2(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setTypeConstraintData (btTypedConstraintDoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_typeConstraintData_set(swigCPtr, this,
btTypedConstraintDoubleData.getCPtr(value), value);
}
public btTypedConstraintDoubleData getTypeConstraintData () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_typeConstraintData_get(swigCPtr, this);
return (cPtr == 0) ? null : new btTypedConstraintDoubleData(cPtr, false);
}
public void setRbAFrame (btTransformDoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rbAFrame_set(swigCPtr, this, btTransformDoubleData.getCPtr(value),
value);
}
public btTransformDoubleData getRbAFrame () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rbAFrame_get(swigCPtr, this);
return (cPtr == 0) ? null : new btTransformDoubleData(cPtr, false);
}
public void setRbBFrame (btTransformDoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rbBFrame_set(swigCPtr, this, btTransformDoubleData.getCPtr(value),
value);
}
public btTransformDoubleData getRbBFrame () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rbBFrame_get(swigCPtr, this);
return (cPtr == 0) ? null : new btTransformDoubleData(cPtr, false);
}
public void setLinearUpperLimit (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearUpperLimit_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearUpperLimit () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearUpperLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearLowerLimit (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearLowerLimit_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearLowerLimit () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearLowerLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearBounce (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearBounce_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearBounce () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearBounce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearStopERP (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearStopERP_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearStopERP () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearStopERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearStopCFM (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearStopCFM_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearStopCFM () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearStopCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearMotorERP (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMotorERP_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearMotorERP () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMotorERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearMotorCFM (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMotorCFM_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getLinearMotorCFM () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMotorCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearTargetVelocity (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearTargetVelocity_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearTargetVelocity () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearTargetVelocity_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearMaxMotorForce (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMaxMotorForce_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearMaxMotorForce () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearMaxMotorForce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearServoTarget (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearServoTarget_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearServoTarget () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearServoTarget_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearSpringStiffness (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringStiffness_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearSpringStiffness () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringStiffness_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearSpringDamping (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringDamping_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearSpringDamping () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringDamping_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearEquilibriumPoint (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEquilibriumPoint_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getLinearEquilibriumPoint () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEquilibriumPoint_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setLinearEnableMotor (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEnableMotor_set(swigCPtr, this, value);
}
public String getLinearEnableMotor () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEnableMotor_get(swigCPtr, this);
}
public void setLinearServoMotor (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearServoMotor_set(swigCPtr, this, value);
}
public String getLinearServoMotor () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearServoMotor_get(swigCPtr, this);
}
public void setLinearEnableSpring (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEnableSpring_set(swigCPtr, this, value);
}
public String getLinearEnableSpring () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearEnableSpring_get(swigCPtr, this);
}
public void setLinearSpringStiffnessLimited (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringStiffnessLimited_set(swigCPtr, this, value);
}
public String getLinearSpringStiffnessLimited () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringStiffnessLimited_get(swigCPtr, this);
}
public void setLinearSpringDampingLimited (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringDampingLimited_set(swigCPtr, this, value);
}
public String getLinearSpringDampingLimited () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_linearSpringDampingLimited_get(swigCPtr, this);
}
public void setPadding1 (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_padding1_set(swigCPtr, this, value);
}
public String getPadding1 () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_padding1_get(swigCPtr, this);
}
public void setAngularUpperLimit (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularUpperLimit_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularUpperLimit () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularUpperLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularLowerLimit (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularLowerLimit_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularLowerLimit () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularLowerLimit_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularBounce (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularBounce_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getAngularBounce () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularBounce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularStopERP (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularStopERP_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getAngularStopERP () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularStopERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularStopCFM (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularStopCFM_set(swigCPtr, this, btVector3DoubleData.getCPtr(value),
value);
}
public btVector3DoubleData getAngularStopCFM () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularStopCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularMotorERP (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMotorERP_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularMotorERP () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMotorERP_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularMotorCFM (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMotorCFM_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularMotorCFM () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMotorCFM_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularTargetVelocity (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularTargetVelocity_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularTargetVelocity () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularTargetVelocity_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularMaxMotorForce (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMaxMotorForce_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularMaxMotorForce () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularMaxMotorForce_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularServoTarget (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularServoTarget_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularServoTarget () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularServoTarget_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularSpringStiffness (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringStiffness_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularSpringStiffness () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringStiffness_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularSpringDamping (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringDamping_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularSpringDamping () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringDamping_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularEquilibriumPoint (btVector3DoubleData value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEquilibriumPoint_set(swigCPtr, this,
btVector3DoubleData.getCPtr(value), value);
}
public btVector3DoubleData getAngularEquilibriumPoint () {
long cPtr = DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEquilibriumPoint_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3DoubleData(cPtr, false);
}
public void setAngularEnableMotor (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEnableMotor_set(swigCPtr, this, value);
}
public String getAngularEnableMotor () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEnableMotor_get(swigCPtr, this);
}
public void setAngularServoMotor (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularServoMotor_set(swigCPtr, this, value);
}
public String getAngularServoMotor () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularServoMotor_get(swigCPtr, this);
}
public void setAngularEnableSpring (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEnableSpring_set(swigCPtr, this, value);
}
public String getAngularEnableSpring () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularEnableSpring_get(swigCPtr, this);
}
public void setAngularSpringStiffnessLimited (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringStiffnessLimited_set(swigCPtr, this, value);
}
public String getAngularSpringStiffnessLimited () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringStiffnessLimited_get(swigCPtr, this);
}
public void setAngularSpringDampingLimited (String value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringDampingLimited_set(swigCPtr, this, value);
}
public String getAngularSpringDampingLimited () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_angularSpringDampingLimited_get(swigCPtr, this);
}
public void setRotateOrder (int value) {
DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rotateOrder_set(swigCPtr, this, value);
}
public int getRotateOrder () {
return DynamicsJNI.btGeneric6DofSpring2ConstraintDoubleData2_rotateOrder_get(swigCPtr, this);
}
public btGeneric6DofSpring2ConstraintDoubleData2 () {
this(DynamicsJNI.new_btGeneric6DofSpring2ConstraintDoubleData2(), true);
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtClipboard.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt;
import com.badlogic.gdx.utils.Clipboard;
/** Basic implementation of clipboard in GWT. Paste only works inside the libGDX application. */
public class GwtClipboard implements Clipboard {
private boolean requestedWritePermissions = false;
private boolean hasWritePermissions = true;
private final ClipboardWriteHandler writeHandler = new ClipboardWriteHandler();
private String content = "";
@Override
public boolean hasContents () {
String contents = getContents();
return contents != null && !contents.isEmpty();
}
@Override
public String getContents () {
return content;
}
@Override
public void setContents (String content) {
this.content = content;
if (requestedWritePermissions || GwtApplication.agentInfo().isFirefox()) {
if (hasWritePermissions) setContentJSNI(content);
} else {
GwtPermissions.queryPermission("clipboard-write", writeHandler);
requestedWritePermissions = true;
}
}
private native void setContentJSNI (String content) /*-{
if ("clipboard" in $wnd.navigator) {
$wnd.navigator.clipboard.writeText(content);
}
}-*/;
private class ClipboardWriteHandler implements GwtPermissions.GwtPermissionResult {
@Override
public void granted () {
hasWritePermissions = true;
setContentJSNI(content);
}
@Override
public void denied () {
hasWritePermissions = false;
}
@Override
public void prompt () {
hasWritePermissions = true;
setContentJSNI(content);
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt;
import com.badlogic.gdx.utils.Clipboard;
/** Basic implementation of clipboard in GWT. Paste only works inside the libGDX application. */
public class GwtClipboard implements Clipboard {
private boolean requestedWritePermissions = false;
private boolean hasWritePermissions = true;
private final ClipboardWriteHandler writeHandler = new ClipboardWriteHandler();
private String content = "";
@Override
public boolean hasContents () {
String contents = getContents();
return contents != null && !contents.isEmpty();
}
@Override
public String getContents () {
return content;
}
@Override
public void setContents (String content) {
this.content = content;
if (requestedWritePermissions || GwtApplication.agentInfo().isFirefox()) {
if (hasWritePermissions) setContentJSNI(content);
} else {
GwtPermissions.queryPermission("clipboard-write", writeHandler);
requestedWritePermissions = true;
}
}
private native void setContentJSNI (String content) /*-{
if ("clipboard" in $wnd.navigator) {
$wnd.navigator.clipboard.writeText(content);
}
}-*/;
private class ClipboardWriteHandler implements GwtPermissions.GwtPermissionResult {
@Override
public void granted () {
hasWritePermissions = true;
setContentJSNI(content);
}
@Override
public void denied () {
hasWritePermissions = false;
}
@Override
public void prompt () {
hasWritePermissions = true;
setContentJSNI(content);
}
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./gdx/src/com/badlogic/gdx/utils/ScreenUtils.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.utils;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Blending;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
/** Class with static helper methods related to currently bound OpenGL frame buffer, including access to the current OpenGL
* FrameBuffer. These methods can be used to get the entire screen content or a portion thereof.
*
* @author espitz */
public final class ScreenUtils {
/** Clears the color buffers with the specified Color.
* @param color Color to clear the color buffers with. */
public static void clear (Color color) {
clear(color.r, color.g, color.b, color.a, false);
}
/** Clears the color buffers with the specified color. */
public static void clear (float r, float g, float b, float a) {
clear(r, g, b, a, false);
}
/** Clears the color buffers and optionally the depth buffer.
* @param color Color to clear the color buffers with.
* @param clearDepth Clears the depth buffer if true. */
public static void clear (Color color, boolean clearDepth) {
clear(color.r, color.g, color.b, color.a, clearDepth);
}
/** Clears the color buffers and optionally the depth buffer.
* @param clearDepth Clears the depth buffer if true. */
public static void clear (float r, float g, float b, float a, boolean clearDepth) {
Gdx.gl.glClearColor(r, g, b, a);
int mask = GL20.GL_COLOR_BUFFER_BIT;
if (clearDepth) mask = mask | GL20.GL_DEPTH_BUFFER_BIT;
Gdx.gl.glClear(mask);
}
/** Returns the current framebuffer contents as a {@link TextureRegion} with a width and height equal to the current screen
* size. The base {@link Texture} always has {@link MathUtils#nextPowerOfTwo} dimensions and RGBA8888 {@link Format}. It can be
* accessed via {@link TextureRegion#getTexture}. The texture is not managed and has to be reloaded manually on a context loss.
* The returned TextureRegion is flipped along the Y axis by default. */
public static TextureRegion getFrameBufferTexture () {
final int w = Gdx.graphics.getBackBufferWidth();
final int h = Gdx.graphics.getBackBufferHeight();
return getFrameBufferTexture(0, 0, w, h);
}
/** Returns a portion of the current framebuffer contents specified by x, y, width and height as a {@link TextureRegion} with
* the same dimensions. The base {@link Texture} always has {@link MathUtils#nextPowerOfTwo} dimensions and RGBA8888
* {@link Format}. It can be accessed via {@link TextureRegion#getTexture}. This texture is not managed and has to be reloaded
* manually on a context loss. If the width and height specified are larger than the framebuffer dimensions, the Texture will
* be padded accordingly. Pixels that fall outside of the current screen will have RGBA values of 0.
*
* @param x the x position of the framebuffer contents to capture
* @param y the y position of the framebuffer contents to capture
* @param w the width of the framebuffer contents to capture
* @param h the height of the framebuffer contents to capture */
public static TextureRegion getFrameBufferTexture (int x, int y, int w, int h) {
final int potW = MathUtils.nextPowerOfTwo(w);
final int potH = MathUtils.nextPowerOfTwo(h);
final Pixmap pixmap = Pixmap.createFromFrameBuffer(x, y, w, h);
final Pixmap potPixmap = new Pixmap(potW, potH, Format.RGBA8888);
potPixmap.setBlending(Blending.None);
potPixmap.drawPixmap(pixmap, 0, 0);
Texture texture = new Texture(potPixmap);
TextureRegion textureRegion = new TextureRegion(texture, 0, h, w, -h);
potPixmap.dispose();
pixmap.dispose();
return textureRegion;
}
/** @deprecated use {@link Pixmap#createFromFrameBuffer(int, int, int, int)} instead. */
@Deprecated
public static Pixmap getFrameBufferPixmap (int x, int y, int w, int h) {
return Pixmap.createFromFrameBuffer(x, y, w, h);
}
/** Returns the current framebuffer contents as a byte[] array with a length equal to screen width * height * 4. The byte[]
* will always contain RGBA8888 data. Because of differences in screen and image origins the framebuffer contents should be
* flipped along the Y axis if you intend save them to disk as a bitmap. Flipping is not a cheap operation, so use this
* functionality wisely.
*
* @param flipY whether to flip pixels along Y axis */
public static byte[] getFrameBufferPixels (boolean flipY) {
final int w = Gdx.graphics.getBackBufferWidth();
final int h = Gdx.graphics.getBackBufferHeight();
return getFrameBufferPixels(0, 0, w, h, flipY);
}
/** Returns a portion of the current framebuffer contents specified by x, y, width and height, as a byte[] array with a length
* equal to the specified width * height * 4. The byte[] will always contain RGBA8888 data. If the width and height specified
* are larger than the framebuffer dimensions, the Texture will be padded accordingly. Pixels that fall outside of the current
* screen will have RGBA values of 0. Because of differences in screen and image origins the framebuffer contents should be
* flipped along the Y axis if you intend save them to disk as a bitmap. Flipping is not a cheap operation, so use this
* functionality wisely.
*
* @param flipY whether to flip pixels along Y axis */
public static byte[] getFrameBufferPixels (int x, int y, int w, int h, boolean flipY) {
Gdx.gl.glPixelStorei(GL20.GL_PACK_ALIGNMENT, 1);
final ByteBuffer pixels = BufferUtils.newByteBuffer(w * h * 4);
Gdx.gl.glReadPixels(x, y, w, h, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixels);
final int numBytes = w * h * 4;
byte[] lines = new byte[numBytes];
if (flipY) {
final int numBytesPerLine = w * 4;
for (int i = 0; i < h; i++) {
((Buffer)pixels).position((h - i - 1) * numBytesPerLine);
pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
}
} else {
((Buffer)pixels).clear();
pixels.get(lines);
}
return lines;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.utils;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Blending;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
/** Class with static helper methods related to currently bound OpenGL frame buffer, including access to the current OpenGL
* FrameBuffer. These methods can be used to get the entire screen content or a portion thereof.
*
* @author espitz */
public final class ScreenUtils {
/** Clears the color buffers with the specified Color.
* @param color Color to clear the color buffers with. */
public static void clear (Color color) {
clear(color.r, color.g, color.b, color.a, false);
}
/** Clears the color buffers with the specified color. */
public static void clear (float r, float g, float b, float a) {
clear(r, g, b, a, false);
}
/** Clears the color buffers and optionally the depth buffer.
* @param color Color to clear the color buffers with.
* @param clearDepth Clears the depth buffer if true. */
public static void clear (Color color, boolean clearDepth) {
clear(color.r, color.g, color.b, color.a, clearDepth);
}
/** Clears the color buffers and optionally the depth buffer.
* @param clearDepth Clears the depth buffer if true. */
public static void clear (float r, float g, float b, float a, boolean clearDepth) {
Gdx.gl.glClearColor(r, g, b, a);
int mask = GL20.GL_COLOR_BUFFER_BIT;
if (clearDepth) mask = mask | GL20.GL_DEPTH_BUFFER_BIT;
Gdx.gl.glClear(mask);
}
/** Returns the current framebuffer contents as a {@link TextureRegion} with a width and height equal to the current screen
* size. The base {@link Texture} always has {@link MathUtils#nextPowerOfTwo} dimensions and RGBA8888 {@link Format}. It can be
* accessed via {@link TextureRegion#getTexture}. The texture is not managed and has to be reloaded manually on a context loss.
* The returned TextureRegion is flipped along the Y axis by default. */
public static TextureRegion getFrameBufferTexture () {
final int w = Gdx.graphics.getBackBufferWidth();
final int h = Gdx.graphics.getBackBufferHeight();
return getFrameBufferTexture(0, 0, w, h);
}
/** Returns a portion of the current framebuffer contents specified by x, y, width and height as a {@link TextureRegion} with
* the same dimensions. The base {@link Texture} always has {@link MathUtils#nextPowerOfTwo} dimensions and RGBA8888
* {@link Format}. It can be accessed via {@link TextureRegion#getTexture}. This texture is not managed and has to be reloaded
* manually on a context loss. If the width and height specified are larger than the framebuffer dimensions, the Texture will
* be padded accordingly. Pixels that fall outside of the current screen will have RGBA values of 0.
*
* @param x the x position of the framebuffer contents to capture
* @param y the y position of the framebuffer contents to capture
* @param w the width of the framebuffer contents to capture
* @param h the height of the framebuffer contents to capture */
public static TextureRegion getFrameBufferTexture (int x, int y, int w, int h) {
final int potW = MathUtils.nextPowerOfTwo(w);
final int potH = MathUtils.nextPowerOfTwo(h);
final Pixmap pixmap = Pixmap.createFromFrameBuffer(x, y, w, h);
final Pixmap potPixmap = new Pixmap(potW, potH, Format.RGBA8888);
potPixmap.setBlending(Blending.None);
potPixmap.drawPixmap(pixmap, 0, 0);
Texture texture = new Texture(potPixmap);
TextureRegion textureRegion = new TextureRegion(texture, 0, h, w, -h);
potPixmap.dispose();
pixmap.dispose();
return textureRegion;
}
/** @deprecated use {@link Pixmap#createFromFrameBuffer(int, int, int, int)} instead. */
@Deprecated
public static Pixmap getFrameBufferPixmap (int x, int y, int w, int h) {
return Pixmap.createFromFrameBuffer(x, y, w, h);
}
/** Returns the current framebuffer contents as a byte[] array with a length equal to screen width * height * 4. The byte[]
* will always contain RGBA8888 data. Because of differences in screen and image origins the framebuffer contents should be
* flipped along the Y axis if you intend save them to disk as a bitmap. Flipping is not a cheap operation, so use this
* functionality wisely.
*
* @param flipY whether to flip pixels along Y axis */
public static byte[] getFrameBufferPixels (boolean flipY) {
final int w = Gdx.graphics.getBackBufferWidth();
final int h = Gdx.graphics.getBackBufferHeight();
return getFrameBufferPixels(0, 0, w, h, flipY);
}
/** Returns a portion of the current framebuffer contents specified by x, y, width and height, as a byte[] array with a length
* equal to the specified width * height * 4. The byte[] will always contain RGBA8888 data. If the width and height specified
* are larger than the framebuffer dimensions, the Texture will be padded accordingly. Pixels that fall outside of the current
* screen will have RGBA values of 0. Because of differences in screen and image origins the framebuffer contents should be
* flipped along the Y axis if you intend save them to disk as a bitmap. Flipping is not a cheap operation, so use this
* functionality wisely.
*
* @param flipY whether to flip pixels along Y axis */
public static byte[] getFrameBufferPixels (int x, int y, int w, int h, boolean flipY) {
Gdx.gl.glPixelStorei(GL20.GL_PACK_ALIGNMENT, 1);
final ByteBuffer pixels = BufferUtils.newByteBuffer(w * h * 4);
Gdx.gl.glReadPixels(x, y, w, h, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, pixels);
final int numBytes = w * h * 4;
byte[] lines = new byte[numBytes];
if (flipY) {
final int numBytesPerLine = w * 4;
for (int i = 0; i < h; i++) {
((Buffer)pixels).position((h - i - 1) * numBytesPerLine);
pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
}
} else {
((Buffer)pixels).clear();
pixels.get(lines);
}
return lines;
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-lwjgl3/src/com/badlogic/gdx/backends/lwjgl3/audio/Ogg.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl3.audio;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.StreamUtils;
import org.lwjgl.stb.STBVorbis;
import org.lwjgl.system.MemoryStack;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
/** @author Nathan Sweet */
public class Ogg {
static public class Music extends OpenALMusic {
private OggInputStream input;
private OggInputStream previousInput;
public Music (OpenALLwjgl3Audio audio, FileHandle file) {
super(audio, file);
if (audio.noDevice) return;
input = new OggInputStream(file.read());
setup(input.getChannels(), input.getSampleRate());
}
public int read (byte[] buffer) {
if (input == null) {
input = new OggInputStream(file.read(), previousInput);
setup(input.getChannels(), input.getSampleRate());
previousInput = null; // release this reference
}
return input.read(buffer);
}
public void reset () {
StreamUtils.closeQuietly(input);
previousInput = null;
input = null;
}
@Override
protected void loop () {
StreamUtils.closeQuietly(input);
previousInput = input;
input = null;
}
}
static public class Sound extends OpenALSound {
public Sound (OpenALLwjgl3Audio audio, FileHandle file) {
super(audio);
if (audio.noDevice) return;
// put the encoded audio data in a ByteBuffer
byte[] streamData = file.readBytes();
ByteBuffer encodedData = BufferUtils.newByteBuffer(streamData.length);
encodedData.put(streamData);
encodedData.flip();
try (MemoryStack stack = MemoryStack.stackPush()) {
final IntBuffer channelsBuffer = stack.mallocInt(1);
final IntBuffer sampleRateBuffer = stack.mallocInt(1);
// decode
final ShortBuffer decodedData = STBVorbis.stb_vorbis_decode_memory(encodedData, channelsBuffer, sampleRateBuffer);
int channels = channelsBuffer.get(0);
int sampleRate = sampleRateBuffer.get(0);
if (decodedData == null) {
throw new GdxRuntimeException("Error decoding OGG file: " + file);
} else if (channels < 1 || channels > 2) {
throw new GdxRuntimeException("Error decoding OGG file, unsupported number of channels: " + file);
}
setup(decodedData, channels, sampleRate);
}
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl3.audio;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.StreamUtils;
import org.lwjgl.stb.STBVorbis;
import org.lwjgl.system.MemoryStack;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
/** @author Nathan Sweet */
public class Ogg {
static public class Music extends OpenALMusic {
private OggInputStream input;
private OggInputStream previousInput;
public Music (OpenALLwjgl3Audio audio, FileHandle file) {
super(audio, file);
if (audio.noDevice) return;
input = new OggInputStream(file.read());
setup(input.getChannels(), input.getSampleRate());
}
public int read (byte[] buffer) {
if (input == null) {
input = new OggInputStream(file.read(), previousInput);
setup(input.getChannels(), input.getSampleRate());
previousInput = null; // release this reference
}
return input.read(buffer);
}
public void reset () {
StreamUtils.closeQuietly(input);
previousInput = null;
input = null;
}
@Override
protected void loop () {
StreamUtils.closeQuietly(input);
previousInput = input;
input = null;
}
}
static public class Sound extends OpenALSound {
public Sound (OpenALLwjgl3Audio audio, FileHandle file) {
super(audio);
if (audio.noDevice) return;
// put the encoded audio data in a ByteBuffer
byte[] streamData = file.readBytes();
ByteBuffer encodedData = BufferUtils.newByteBuffer(streamData.length);
encodedData.put(streamData);
encodedData.flip();
try (MemoryStack stack = MemoryStack.stackPush()) {
final IntBuffer channelsBuffer = stack.mallocInt(1);
final IntBuffer sampleRateBuffer = stack.mallocInt(1);
// decode
final ShortBuffer decodedData = STBVorbis.stb_vorbis_decode_memory(encodedData, channelsBuffer, sampleRateBuffer);
int channels = channelsBuffer.get(0);
int sampleRate = sampleRateBuffer.get(0);
if (decodedData == null) {
throw new GdxRuntimeException("Error decoding OGG file: " + file);
} else if (channels < 1 || channels > 2) {
throw new GdxRuntimeException("Error decoding OGG file, unsupported number of channels: " + file);
}
setup(decodedData, channels, sampleRate);
}
}
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-tools/src/com/badlogic/gdx/tools/flame/CustomCardLayout.java |
package com.badlogic.gdx.tools.flame;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
/** @author Inferno */
public class CustomCardLayout extends CardLayout {
@Override
public Dimension preferredLayoutSize (Container parent) {
Component component = getCurrentCard(parent);
return component != null ? component.getPreferredSize() : super.preferredLayoutSize(parent);
}
public <K> K getCurrentCard (Container container) {
Component c[] = container.getComponents();
int i = 0;
int j = c.length;
while (i < j) {
if (c[i].isVisible()) {
return (K)c[i];
} else
i++;
}
return null;
}
}
|
package com.badlogic.gdx.tools.flame;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
/** @author Inferno */
public class CustomCardLayout extends CardLayout {
@Override
public Dimension preferredLayoutSize (Container parent) {
Component component = getCurrentCard(parent);
return component != null ? component.getPreferredSize() : super.preferredLayoutSize(parent);
}
public <K> K getCurrentCard (Container container) {
Component c[] = container.getComponents();
int i = 0;
int j = c.length;
while (i < j) {
if (c[i].isVisible()) {
return (K)c[i];
} else
i++;
}
return null;
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./gdx/src/com/badlogic/gdx/graphics/g2d/PolygonRegion.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics.g2d;
/** Defines a polygon shape on top of a texture region to avoid drawing transparent pixels.
* @see PolygonRegionLoader
* @author Stefan Bachmann
* @author Nathan Sweet */
public class PolygonRegion {
final float[] textureCoords; // texture coordinates in atlas coordinates
final float[] vertices; // pixel coordinates relative to source image.
final short[] triangles;
final TextureRegion region;
/** Creates a PolygonRegion by triangulating the polygon coordinates in vertices and calculates uvs based on that.
* TextureRegion can come from an atlas.
* @param region the region used for drawing
* @param vertices contains 2D polygon coordinates in pixels relative to source region */
public PolygonRegion (TextureRegion region, float[] vertices, short[] triangles) {
this.region = region;
this.vertices = vertices;
this.triangles = triangles;
float[] textureCoords = this.textureCoords = new float[vertices.length];
float u = region.u, v = region.v;
float uvWidth = region.u2 - u;
float uvHeight = region.v2 - v;
int width = region.regionWidth;
int height = region.regionHeight;
for (int i = 0, n = vertices.length; i < n; i += 2) {
textureCoords[i] = u + uvWidth * (vertices[i] / width);
textureCoords[i + 1] = v + uvHeight * (1 - (vertices[i + 1] / height));
}
}
/** Returns the vertices in local space. */
public float[] getVertices () {
return vertices;
}
public short[] getTriangles () {
return triangles;
}
public float[] getTextureCoords () {
return textureCoords;
}
public TextureRegion getRegion () {
return region;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics.g2d;
/** Defines a polygon shape on top of a texture region to avoid drawing transparent pixels.
* @see PolygonRegionLoader
* @author Stefan Bachmann
* @author Nathan Sweet */
public class PolygonRegion {
final float[] textureCoords; // texture coordinates in atlas coordinates
final float[] vertices; // pixel coordinates relative to source image.
final short[] triangles;
final TextureRegion region;
/** Creates a PolygonRegion by triangulating the polygon coordinates in vertices and calculates uvs based on that.
* TextureRegion can come from an atlas.
* @param region the region used for drawing
* @param vertices contains 2D polygon coordinates in pixels relative to source region */
public PolygonRegion (TextureRegion region, float[] vertices, short[] triangles) {
this.region = region;
this.vertices = vertices;
this.triangles = triangles;
float[] textureCoords = this.textureCoords = new float[vertices.length];
float u = region.u, v = region.v;
float uvWidth = region.u2 - u;
float uvHeight = region.v2 - v;
int width = region.regionWidth;
int height = region.regionHeight;
for (int i = 0, n = vertices.length; i < n; i += 2) {
textureCoords[i] = u + uvWidth * (vertices[i] / width);
textureCoords[i + 1] = v + uvHeight * (1 - (vertices[i + 1] / height));
}
}
/** Returns the vertices in local space. */
public float[] getVertices () {
return vertices;
}
public short[] getTriangles () {
return triangles;
}
public float[] getTextureCoords () {
return textureCoords;
}
public TextureRegion getRegion () {
return region;
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./gdx/src/com/badlogic/gdx/graphics/g3d/particles/batches/PointSpriteParticleBatch.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.particles.batches;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.DepthTestAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.particles.ParallelArray.FloatChannel;
import com.badlogic.gdx.graphics.g3d.particles.ParticleChannels;
import com.badlogic.gdx.graphics.g3d.particles.ParticleShader;
import com.badlogic.gdx.graphics.g3d.particles.ParticleShader.ParticleType;
import com.badlogic.gdx.graphics.g3d.particles.ResourceData;
import com.badlogic.gdx.graphics.g3d.particles.ResourceData.SaveData;
import com.badlogic.gdx.graphics.g3d.particles.renderers.PointSpriteControllerRenderData;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
/** This class is used to draw particles as point sprites.
* @author Inferno */
public class PointSpriteParticleBatch extends BufferedParticleBatch<PointSpriteControllerRenderData> {
private static boolean pointSpritesEnabled = false;
protected static final Vector3 TMP_V1 = new Vector3();
protected static final int sizeAndRotationUsage = 1 << 9;
protected static final VertexAttributes CPU_ATTRIBUTES = new VertexAttributes(
new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE),
new VertexAttribute(Usage.ColorUnpacked, 4, ShaderProgram.COLOR_ATTRIBUTE),
new VertexAttribute(Usage.TextureCoordinates, 4, "a_region"),
new VertexAttribute(sizeAndRotationUsage, 3, "a_sizeAndRotation"));
protected static final int CPU_VERTEX_SIZE = (short)(CPU_ATTRIBUTES.vertexSize / 4),
CPU_POSITION_OFFSET = (short)(CPU_ATTRIBUTES.findByUsage(Usage.Position).offset / 4),
CPU_COLOR_OFFSET = (short)(CPU_ATTRIBUTES.findByUsage(Usage.ColorUnpacked).offset / 4),
CPU_REGION_OFFSET = (short)(CPU_ATTRIBUTES.findByUsage(Usage.TextureCoordinates).offset / 4),
CPU_SIZE_AND_ROTATION_OFFSET = (short)(CPU_ATTRIBUTES.findByUsage(sizeAndRotationUsage).offset / 4);
private static void enablePointSprites () {
Gdx.gl.glEnable(GL20.GL_VERTEX_PROGRAM_POINT_SIZE);
if (Gdx.app.getType() == ApplicationType.Desktop) {
Gdx.gl.glEnable(0x8861); // GL_POINT_OES
}
pointSpritesEnabled = true;
}
private float[] vertices;
Renderable renderable;
protected BlendingAttribute blendingAttribute;
protected DepthTestAttribute depthTestAttribute;
public PointSpriteParticleBatch () {
this(1000);
}
public PointSpriteParticleBatch (int capacity) {
this(capacity, new ParticleShader.Config(ParticleType.Point));
}
public PointSpriteParticleBatch (int capacity, ParticleShader.Config shaderConfig) {
this(capacity, shaderConfig, null, null);
}
public PointSpriteParticleBatch (int capacity, ParticleShader.Config shaderConfig, BlendingAttribute blendingAttribute,
DepthTestAttribute depthTestAttribute) {
super(PointSpriteControllerRenderData.class);
if (!pointSpritesEnabled) enablePointSprites();
this.blendingAttribute = blendingAttribute;
this.depthTestAttribute = depthTestAttribute;
if (this.blendingAttribute == null)
this.blendingAttribute = new BlendingAttribute(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA, 1f);
if (this.depthTestAttribute == null) this.depthTestAttribute = new DepthTestAttribute(GL20.GL_LEQUAL, false);
allocRenderable();
ensureCapacity(capacity);
renderable.shader = new ParticleShader(renderable, shaderConfig);
renderable.shader.init();
}
@Override
protected void allocParticlesData (int capacity) {
vertices = new float[capacity * CPU_VERTEX_SIZE];
if (renderable.meshPart.mesh != null) renderable.meshPart.mesh.dispose();
renderable.meshPart.mesh = new Mesh(false, capacity, 0, CPU_ATTRIBUTES);
}
protected void allocRenderable () {
renderable = new Renderable();
renderable.meshPart.primitiveType = GL20.GL_POINTS;
renderable.meshPart.offset = 0;
renderable.material = new Material(blendingAttribute, depthTestAttribute, TextureAttribute.createDiffuse((Texture)null));
}
public void setTexture (Texture texture) {
TextureAttribute attribute = (TextureAttribute)renderable.material.get(TextureAttribute.Diffuse);
attribute.textureDescription.texture = texture;
}
public Texture getTexture () {
TextureAttribute attribute = (TextureAttribute)renderable.material.get(TextureAttribute.Diffuse);
return attribute.textureDescription.texture;
}
public BlendingAttribute getBlendingAttribute () {
return blendingAttribute;
}
@Override
protected void flush (int[] offsets) {
int tp = 0;
for (PointSpriteControllerRenderData data : renderData) {
FloatChannel scaleChannel = data.scaleChannel;
FloatChannel regionChannel = data.regionChannel;
FloatChannel positionChannel = data.positionChannel;
FloatChannel colorChannel = data.colorChannel;
FloatChannel rotationChannel = data.rotationChannel;
for (int p = 0; p < data.controller.particles.size; ++p, ++tp) {
int offset = offsets[tp] * CPU_VERTEX_SIZE;
int regionOffset = p * regionChannel.strideSize;
int positionOffset = p * positionChannel.strideSize;
int colorOffset = p * colorChannel.strideSize;
int rotationOffset = p * rotationChannel.strideSize;
vertices[offset + CPU_POSITION_OFFSET] = positionChannel.data[positionOffset + ParticleChannels.XOffset];
vertices[offset + CPU_POSITION_OFFSET + 1] = positionChannel.data[positionOffset + ParticleChannels.YOffset];
vertices[offset + CPU_POSITION_OFFSET + 2] = positionChannel.data[positionOffset + ParticleChannels.ZOffset];
vertices[offset + CPU_COLOR_OFFSET] = colorChannel.data[colorOffset + ParticleChannels.RedOffset];
vertices[offset + CPU_COLOR_OFFSET + 1] = colorChannel.data[colorOffset + ParticleChannels.GreenOffset];
vertices[offset + CPU_COLOR_OFFSET + 2] = colorChannel.data[colorOffset + ParticleChannels.BlueOffset];
vertices[offset + CPU_COLOR_OFFSET + 3] = colorChannel.data[colorOffset + ParticleChannels.AlphaOffset];
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET] = scaleChannel.data[p * scaleChannel.strideSize];
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET + 1] = rotationChannel.data[rotationOffset
+ ParticleChannels.CosineOffset];
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET + 2] = rotationChannel.data[rotationOffset
+ ParticleChannels.SineOffset];
vertices[offset + CPU_REGION_OFFSET] = regionChannel.data[regionOffset + ParticleChannels.UOffset];
vertices[offset + CPU_REGION_OFFSET + 1] = regionChannel.data[regionOffset + ParticleChannels.VOffset];
vertices[offset + CPU_REGION_OFFSET + 2] = regionChannel.data[regionOffset + ParticleChannels.U2Offset];
vertices[offset + CPU_REGION_OFFSET + 3] = regionChannel.data[regionOffset + ParticleChannels.V2Offset];
}
}
renderable.meshPart.size = bufferedParticlesCount;
renderable.meshPart.mesh.setVertices(vertices, 0, bufferedParticlesCount * CPU_VERTEX_SIZE);
renderable.meshPart.update();
}
@Override
public void getRenderables (Array<Renderable> renderables, Pool<Renderable> pool) {
if (bufferedParticlesCount > 0) renderables.add(pool.obtain().set(renderable));
}
@Override
public void save (AssetManager manager, ResourceData resources) {
SaveData data = resources.createSaveData("pointSpriteBatch");
data.saveAsset(manager.getAssetFileName(getTexture()), Texture.class);
}
@Override
public void load (AssetManager manager, ResourceData resources) {
SaveData data = resources.getSaveData("pointSpriteBatch");
if (data != null) setTexture((Texture)manager.get(data.loadAsset()));
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.particles.batches;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.DepthTestAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.particles.ParallelArray.FloatChannel;
import com.badlogic.gdx.graphics.g3d.particles.ParticleChannels;
import com.badlogic.gdx.graphics.g3d.particles.ParticleShader;
import com.badlogic.gdx.graphics.g3d.particles.ParticleShader.ParticleType;
import com.badlogic.gdx.graphics.g3d.particles.ResourceData;
import com.badlogic.gdx.graphics.g3d.particles.ResourceData.SaveData;
import com.badlogic.gdx.graphics.g3d.particles.renderers.PointSpriteControllerRenderData;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
/** This class is used to draw particles as point sprites.
* @author Inferno */
public class PointSpriteParticleBatch extends BufferedParticleBatch<PointSpriteControllerRenderData> {
private static boolean pointSpritesEnabled = false;
protected static final Vector3 TMP_V1 = new Vector3();
protected static final int sizeAndRotationUsage = 1 << 9;
protected static final VertexAttributes CPU_ATTRIBUTES = new VertexAttributes(
new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE),
new VertexAttribute(Usage.ColorUnpacked, 4, ShaderProgram.COLOR_ATTRIBUTE),
new VertexAttribute(Usage.TextureCoordinates, 4, "a_region"),
new VertexAttribute(sizeAndRotationUsage, 3, "a_sizeAndRotation"));
protected static final int CPU_VERTEX_SIZE = (short)(CPU_ATTRIBUTES.vertexSize / 4),
CPU_POSITION_OFFSET = (short)(CPU_ATTRIBUTES.findByUsage(Usage.Position).offset / 4),
CPU_COLOR_OFFSET = (short)(CPU_ATTRIBUTES.findByUsage(Usage.ColorUnpacked).offset / 4),
CPU_REGION_OFFSET = (short)(CPU_ATTRIBUTES.findByUsage(Usage.TextureCoordinates).offset / 4),
CPU_SIZE_AND_ROTATION_OFFSET = (short)(CPU_ATTRIBUTES.findByUsage(sizeAndRotationUsage).offset / 4);
private static void enablePointSprites () {
Gdx.gl.glEnable(GL20.GL_VERTEX_PROGRAM_POINT_SIZE);
if (Gdx.app.getType() == ApplicationType.Desktop) {
Gdx.gl.glEnable(0x8861); // GL_POINT_OES
}
pointSpritesEnabled = true;
}
private float[] vertices;
Renderable renderable;
protected BlendingAttribute blendingAttribute;
protected DepthTestAttribute depthTestAttribute;
public PointSpriteParticleBatch () {
this(1000);
}
public PointSpriteParticleBatch (int capacity) {
this(capacity, new ParticleShader.Config(ParticleType.Point));
}
public PointSpriteParticleBatch (int capacity, ParticleShader.Config shaderConfig) {
this(capacity, shaderConfig, null, null);
}
public PointSpriteParticleBatch (int capacity, ParticleShader.Config shaderConfig, BlendingAttribute blendingAttribute,
DepthTestAttribute depthTestAttribute) {
super(PointSpriteControllerRenderData.class);
if (!pointSpritesEnabled) enablePointSprites();
this.blendingAttribute = blendingAttribute;
this.depthTestAttribute = depthTestAttribute;
if (this.blendingAttribute == null)
this.blendingAttribute = new BlendingAttribute(GL20.GL_ONE, GL20.GL_ONE_MINUS_SRC_ALPHA, 1f);
if (this.depthTestAttribute == null) this.depthTestAttribute = new DepthTestAttribute(GL20.GL_LEQUAL, false);
allocRenderable();
ensureCapacity(capacity);
renderable.shader = new ParticleShader(renderable, shaderConfig);
renderable.shader.init();
}
@Override
protected void allocParticlesData (int capacity) {
vertices = new float[capacity * CPU_VERTEX_SIZE];
if (renderable.meshPart.mesh != null) renderable.meshPart.mesh.dispose();
renderable.meshPart.mesh = new Mesh(false, capacity, 0, CPU_ATTRIBUTES);
}
protected void allocRenderable () {
renderable = new Renderable();
renderable.meshPart.primitiveType = GL20.GL_POINTS;
renderable.meshPart.offset = 0;
renderable.material = new Material(blendingAttribute, depthTestAttribute, TextureAttribute.createDiffuse((Texture)null));
}
public void setTexture (Texture texture) {
TextureAttribute attribute = (TextureAttribute)renderable.material.get(TextureAttribute.Diffuse);
attribute.textureDescription.texture = texture;
}
public Texture getTexture () {
TextureAttribute attribute = (TextureAttribute)renderable.material.get(TextureAttribute.Diffuse);
return attribute.textureDescription.texture;
}
public BlendingAttribute getBlendingAttribute () {
return blendingAttribute;
}
@Override
protected void flush (int[] offsets) {
int tp = 0;
for (PointSpriteControllerRenderData data : renderData) {
FloatChannel scaleChannel = data.scaleChannel;
FloatChannel regionChannel = data.regionChannel;
FloatChannel positionChannel = data.positionChannel;
FloatChannel colorChannel = data.colorChannel;
FloatChannel rotationChannel = data.rotationChannel;
for (int p = 0; p < data.controller.particles.size; ++p, ++tp) {
int offset = offsets[tp] * CPU_VERTEX_SIZE;
int regionOffset = p * regionChannel.strideSize;
int positionOffset = p * positionChannel.strideSize;
int colorOffset = p * colorChannel.strideSize;
int rotationOffset = p * rotationChannel.strideSize;
vertices[offset + CPU_POSITION_OFFSET] = positionChannel.data[positionOffset + ParticleChannels.XOffset];
vertices[offset + CPU_POSITION_OFFSET + 1] = positionChannel.data[positionOffset + ParticleChannels.YOffset];
vertices[offset + CPU_POSITION_OFFSET + 2] = positionChannel.data[positionOffset + ParticleChannels.ZOffset];
vertices[offset + CPU_COLOR_OFFSET] = colorChannel.data[colorOffset + ParticleChannels.RedOffset];
vertices[offset + CPU_COLOR_OFFSET + 1] = colorChannel.data[colorOffset + ParticleChannels.GreenOffset];
vertices[offset + CPU_COLOR_OFFSET + 2] = colorChannel.data[colorOffset + ParticleChannels.BlueOffset];
vertices[offset + CPU_COLOR_OFFSET + 3] = colorChannel.data[colorOffset + ParticleChannels.AlphaOffset];
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET] = scaleChannel.data[p * scaleChannel.strideSize];
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET + 1] = rotationChannel.data[rotationOffset
+ ParticleChannels.CosineOffset];
vertices[offset + CPU_SIZE_AND_ROTATION_OFFSET + 2] = rotationChannel.data[rotationOffset
+ ParticleChannels.SineOffset];
vertices[offset + CPU_REGION_OFFSET] = regionChannel.data[regionOffset + ParticleChannels.UOffset];
vertices[offset + CPU_REGION_OFFSET + 1] = regionChannel.data[regionOffset + ParticleChannels.VOffset];
vertices[offset + CPU_REGION_OFFSET + 2] = regionChannel.data[regionOffset + ParticleChannels.U2Offset];
vertices[offset + CPU_REGION_OFFSET + 3] = regionChannel.data[regionOffset + ParticleChannels.V2Offset];
}
}
renderable.meshPart.size = bufferedParticlesCount;
renderable.meshPart.mesh.setVertices(vertices, 0, bufferedParticlesCount * CPU_VERTEX_SIZE);
renderable.meshPart.update();
}
@Override
public void getRenderables (Array<Renderable> renderables, Pool<Renderable> pool) {
if (bufferedParticlesCount > 0) renderables.add(pool.obtain().set(renderable));
}
@Override
public void save (AssetManager manager, ResourceData resources) {
SaveData data = resources.createSaveData("pointSpriteBatch");
data.saveAsset(manager.getAssetFileName(getTexture()), Texture.class);
}
@Override
public void load (AssetManager manager, ResourceData resources) {
SaveData data = resources.getSaveData("pointSpriteBatch");
if (data != null) setTexture((Texture)manager.get(data.loadAsset()));
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./gdx/src/com/badlogic/gdx/utils/async/AsyncResult.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.utils.async;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/** Returned by {@link AsyncExecutor#submit(AsyncTask)}, allows to poll for the result of the asynch workload.
* @author badlogic */
public class AsyncResult<T> {
private final Future<T> future;
AsyncResult (Future<T> future) {
this.future = future;
}
/** @return whether the {@link AsyncTask} is done */
public boolean isDone () {
return future.isDone();
}
/** @return waits if necessary for the computation to complete and then returns the result
* @throws GdxRuntimeException if there was an error */
public T get () {
try {
return future.get();
} catch (InterruptedException ex) {
return null;
} catch (ExecutionException ex) {
throw new GdxRuntimeException(ex.getCause());
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.utils.async;
import com.badlogic.gdx.utils.GdxRuntimeException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/** Returned by {@link AsyncExecutor#submit(AsyncTask)}, allows to poll for the result of the asynch workload.
* @author badlogic */
public class AsyncResult<T> {
private final Future<T> future;
AsyncResult (Future<T> future) {
this.future = future;
}
/** @return whether the {@link AsyncTask} is done */
public boolean isDone () {
return future.isDone();
}
/** @return waits if necessary for the computation to complete and then returns the result
* @throws GdxRuntimeException if there was an error */
public T get () {
try {
return future.get();
} catch (InterruptedException ex) {
return null;
} catch (ExecutionException ex) {
throw new GdxRuntimeException(ex.getCause());
}
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapModifiedExternalTilesetTest.java |
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.IsometricTiledMapRenderer;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.OrthoCamController;
import com.badlogic.gdx.utils.ScreenUtils;
public class TiledMapModifiedExternalTilesetTest extends GdxTest {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private OrthoCamController cameraController;
private BitmapFont font;
private SpriteBatch batch;
@Override
public void create () {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, (w / h) * 10, 10);
camera.position.set(10.0f, 2.5f, 0.0f);
camera.update();
cameraController = new OrthoCamController(camera);
Gdx.input.setInputProcessor(cameraController);
font = new BitmapFont();
batch = new SpriteBatch();
// These two maps should appear identical -- a ring of grass with water inside and out.
// The original is correct, without the bug fix to TiledMapTileSets.java that acompanies
// this test, the latter appears as all grass.
// map = new TmxMapLoader().load("data/maps/tiled/external-tilesets/test_original.tmx");
map = new TmxMapLoader().load("data/maps/tiled/external-tilesets/test_extended.tmx");
renderer = new IsometricTiledMapRenderer(map, 1f / 32f);
}
@Override
public void render () {
ScreenUtils.clear(0.55f, 0.55f, 0.55f, 1f);
camera.update();
renderer.setView(camera);
renderer.render();
batch.begin();
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
@Override
public void dispose () {
map.dispose();
}
}
|
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.IsometricTiledMapRenderer;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.OrthoCamController;
import com.badlogic.gdx.utils.ScreenUtils;
public class TiledMapModifiedExternalTilesetTest extends GdxTest {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private OrthoCamController cameraController;
private BitmapFont font;
private SpriteBatch batch;
@Override
public void create () {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, (w / h) * 10, 10);
camera.position.set(10.0f, 2.5f, 0.0f);
camera.update();
cameraController = new OrthoCamController(camera);
Gdx.input.setInputProcessor(cameraController);
font = new BitmapFont();
batch = new SpriteBatch();
// These two maps should appear identical -- a ring of grass with water inside and out.
// The original is correct, without the bug fix to TiledMapTileSets.java that acompanies
// this test, the latter appears as all grass.
// map = new TmxMapLoader().load("data/maps/tiled/external-tilesets/test_original.tmx");
map = new TmxMapLoader().load("data/maps/tiled/external-tilesets/test_extended.tmx");
renderer = new IsometricTiledMapRenderer(map, 1f / 32f);
}
@Override
public void render () {
ScreenUtils.clear(0.55f, 0.55f, 0.55f, 1f);
camera.update();
renderer.setView(camera);
renderer.render();
batch.begin();
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
@Override
public void dispose () {
map.dispose();
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./gdx/src/com/badlogic/gdx/utils/Scaling.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.utils;
import com.badlogic.gdx.math.Vector2;
/** Various scaling types for fitting one rectangle into another.
* @author Nathan Sweet */
public abstract class Scaling {
protected static final Vector2 temp = new Vector2();
/** Returns the size of the source scaled to the target. Note the same Vector2 instance is always returned and should never be
* cached. */
public abstract Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight);
/** Scales the source to fit the target while keeping the same aspect ratio. This may cause the source to be smaller than the
* target in one direction. */
public static final Scaling fit = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetRatio > sourceRatio ? targetWidth / sourceWidth : targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fit the target while keeping the same aspect ratio, but the source is not scaled at all if smaller in
* both directions. This may cause the source to be smaller than the target in one or both directions. */
public static final Scaling contain = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetRatio > sourceRatio ? targetWidth / sourceWidth : targetHeight / sourceHeight;
if (scale > 1) scale = 1;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fill the target while keeping the same aspect ratio. This may cause the source to be larger than the
* target in one direction. */
public static final Scaling fill = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetRatio < sourceRatio ? targetWidth / sourceWidth : targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fill the target in the x direction while keeping the same aspect ratio. This may cause the source to
* be smaller or larger than the target in the y direction. */
public static final Scaling fillX = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float scale = targetWidth / sourceWidth;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fill the target in the y direction while keeping the same aspect ratio. This may cause the source to
* be smaller or larger than the target in the x direction. */
public static final Scaling fillY = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float scale = targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fill the target. This may cause the source to not keep the same aspect ratio. */
public static final Scaling stretch = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
temp.x = targetWidth;
temp.y = targetHeight;
return temp;
}
};
/** Scales the source to fill the target in the x direction, without changing the y direction. This may cause the source to not
* keep the same aspect ratio. */
public static final Scaling stretchX = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
temp.x = targetWidth;
temp.y = sourceHeight;
return temp;
}
};
/** Scales the source to fill the target in the y direction, without changing the x direction. This may cause the source to not
* keep the same aspect ratio. */
public static final Scaling stretchY = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
temp.x = sourceWidth;
temp.y = targetHeight;
return temp;
}
};
/** The source is not scaled. */
public static final Scaling none = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
temp.x = sourceWidth;
temp.y = sourceHeight;
return temp;
}
};
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.utils;
import com.badlogic.gdx.math.Vector2;
/** Various scaling types for fitting one rectangle into another.
* @author Nathan Sweet */
public abstract class Scaling {
protected static final Vector2 temp = new Vector2();
/** Returns the size of the source scaled to the target. Note the same Vector2 instance is always returned and should never be
* cached. */
public abstract Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight);
/** Scales the source to fit the target while keeping the same aspect ratio. This may cause the source to be smaller than the
* target in one direction. */
public static final Scaling fit = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetRatio > sourceRatio ? targetWidth / sourceWidth : targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fit the target while keeping the same aspect ratio, but the source is not scaled at all if smaller in
* both directions. This may cause the source to be smaller than the target in one or both directions. */
public static final Scaling contain = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetRatio > sourceRatio ? targetWidth / sourceWidth : targetHeight / sourceHeight;
if (scale > 1) scale = 1;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fill the target while keeping the same aspect ratio. This may cause the source to be larger than the
* target in one direction. */
public static final Scaling fill = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float targetRatio = targetHeight / targetWidth;
float sourceRatio = sourceHeight / sourceWidth;
float scale = targetRatio < sourceRatio ? targetWidth / sourceWidth : targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fill the target in the x direction while keeping the same aspect ratio. This may cause the source to
* be smaller or larger than the target in the y direction. */
public static final Scaling fillX = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float scale = targetWidth / sourceWidth;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fill the target in the y direction while keeping the same aspect ratio. This may cause the source to
* be smaller or larger than the target in the x direction. */
public static final Scaling fillY = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
float scale = targetHeight / sourceHeight;
temp.x = sourceWidth * scale;
temp.y = sourceHeight * scale;
return temp;
}
};
/** Scales the source to fill the target. This may cause the source to not keep the same aspect ratio. */
public static final Scaling stretch = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
temp.x = targetWidth;
temp.y = targetHeight;
return temp;
}
};
/** Scales the source to fill the target in the x direction, without changing the y direction. This may cause the source to not
* keep the same aspect ratio. */
public static final Scaling stretchX = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
temp.x = targetWidth;
temp.y = sourceHeight;
return temp;
}
};
/** Scales the source to fill the target in the y direction, without changing the x direction. This may cause the source to not
* keep the same aspect ratio. */
public static final Scaling stretchY = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
temp.x = sourceWidth;
temp.y = targetHeight;
return temp;
}
};
/** The source is not scaled. */
public static final Scaling none = new Scaling() {
public Vector2 apply (float sourceWidth, float sourceHeight, float targetWidth, float targetHeight) {
temp.x = sourceWidth;
temp.y = sourceHeight;
return temp;
}
};
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btEmptyAlgorithm.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btEmptyAlgorithm extends btCollisionAlgorithm {
private long swigCPtr;
protected btEmptyAlgorithm (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btEmptyAlgorithm_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btEmptyAlgorithm, normally you should not need this constructor it's intended for low-level usage. */
public btEmptyAlgorithm (long cPtr, boolean cMemoryOwn) {
this("btEmptyAlgorithm", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btEmptyAlgorithm_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btEmptyAlgorithm obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btEmptyAlgorithm(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btEmptyAlgorithm (btCollisionAlgorithmConstructionInfo ci) {
this(CollisionJNI.new_btEmptyAlgorithm(btCollisionAlgorithmConstructionInfo.getCPtr(ci), ci), true);
}
static public class CreateFunc extends btCollisionAlgorithmCreateFunc {
private long swigCPtr;
protected CreateFunc (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btEmptyAlgorithm_CreateFunc_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new CreateFunc, normally you should not need this constructor it's intended for low-level usage. */
public CreateFunc (long cPtr, boolean cMemoryOwn) {
this("CreateFunc", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btEmptyAlgorithm_CreateFunc_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (CreateFunc obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btEmptyAlgorithm_CreateFunc(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public CreateFunc () {
this(CollisionJNI.new_btEmptyAlgorithm_CreateFunc(), true);
}
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
public class btEmptyAlgorithm extends btCollisionAlgorithm {
private long swigCPtr;
protected btEmptyAlgorithm (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btEmptyAlgorithm_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btEmptyAlgorithm, normally you should not need this constructor it's intended for low-level usage. */
public btEmptyAlgorithm (long cPtr, boolean cMemoryOwn) {
this("btEmptyAlgorithm", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btEmptyAlgorithm_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btEmptyAlgorithm obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btEmptyAlgorithm(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btEmptyAlgorithm (btCollisionAlgorithmConstructionInfo ci) {
this(CollisionJNI.new_btEmptyAlgorithm(btCollisionAlgorithmConstructionInfo.getCPtr(ci), ci), true);
}
static public class CreateFunc extends btCollisionAlgorithmCreateFunc {
private long swigCPtr;
protected CreateFunc (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btEmptyAlgorithm_CreateFunc_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new CreateFunc, normally you should not need this constructor it's intended for low-level usage. */
public CreateFunc (long cPtr, boolean cMemoryOwn) {
this("CreateFunc", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btEmptyAlgorithm_CreateFunc_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (CreateFunc obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btEmptyAlgorithm_CreateFunc(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public CreateFunc () {
this(CollisionJNI.new_btEmptyAlgorithm_CreateFunc(), true);
}
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtFileHandle.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.gwt.preloader.Preloader;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class GwtFileHandle extends FileHandle {
public final Preloader preloader;
private final String file;
private final FileType type;
public GwtFileHandle (Preloader preloader, String fileName, FileType type) {
if (type != FileType.Internal && type != FileType.Classpath)
throw new GdxRuntimeException("FileType '" + type + "' Not supported in GWT backend");
this.preloader = preloader;
this.file = fixSlashes(fileName);
this.type = type;
}
public GwtFileHandle (String path) {
this.type = FileType.Internal;
this.preloader = ((GwtApplication)Gdx.app).getPreloader();
this.file = fixSlashes(path);
}
/** @return The full url to an asset, e.g. http://localhost:8080/assets/data/shotgun-e5f56587d6f025bff049632853ae4ff9.ogg */
public String getAssetUrl () {
return preloader.baseUrl + preloader.assetNames.get(file, file);
}
public String path () {
return file;
}
public String name () {
int index = file.lastIndexOf('/');
if (index < 0) return file;
return file.substring(index + 1);
}
public String extension () {
String name = name();
int dotIndex = name.lastIndexOf('.');
if (dotIndex == -1) return "";
return name.substring(dotIndex + 1);
}
public String nameWithoutExtension () {
String name = name();
int dotIndex = name.lastIndexOf('.');
if (dotIndex == -1) return name;
return name.substring(0, dotIndex);
}
/** @return the path and filename without the extension, e.g. dir/dir2/file.png -> dir/dir2/file */
public String pathWithoutExtension () {
String path = file;
int dotIndex = path.lastIndexOf('.');
if (dotIndex == -1) return path;
return path.substring(0, dotIndex);
}
public FileType type () {
return type;
}
/** Returns a java.io.File that represents this file handle. Note the returned file will only be usable for
* {@link FileType#Absolute} and {@link FileType#External} file handles. */
public File file () {
throw new GdxRuntimeException("file() not supported in GWT backend");
}
/** Returns a stream for reading this file as bytes.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public InputStream read () {
InputStream in = preloader.read(file);
if (in == null) throw new GdxRuntimeException(file + " does not exist");
return in;
}
/** Returns a buffered stream for reading this file as bytes.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedInputStream read (int bufferSize) {
return new BufferedInputStream(read(), bufferSize);
}
/** Returns a reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public Reader reader () {
return new InputStreamReader(read());
}
/** Returns a reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public Reader reader (String charset) {
try {
return new InputStreamReader(read(), charset);
} catch (UnsupportedEncodingException e) {
throw new GdxRuntimeException("Encoding '" + charset + "' not supported", e);
}
}
/** Returns a buffered reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize) {
return new BufferedReader(reader(), bufferSize);
}
/** Returns a buffered reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize, String charset) {
return new BufferedReader(reader(charset), bufferSize);
}
/** Reads the entire file into a string using the platform's default charset.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString () {
return readString(null);
}
/** Reads the entire file into a string using the specified charset.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString (String charset) {
if (preloader.isText(file)) return preloader.texts.get(file);
return new String(readBytes(), StandardCharsets.UTF_8);
}
/** Reads the entire file into a byte array.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public byte[] readBytes () {
int length = (int)length();
if (length == 0) length = 512;
byte[] buffer = new byte[length];
int position = 0;
try (InputStream input = read()) {
while (true) {
int count = input.read(buffer, position, buffer.length - position);
if (count == -1) break;
position += count;
if (position == buffer.length) {
// Grow buffer.
byte[] newBuffer = new byte[buffer.length * 2];
System.arraycopy(buffer, 0, newBuffer, 0, position);
buffer = newBuffer;
}
}
} catch (IOException ex) {
throw new GdxRuntimeException("Error reading file: " + this, ex);
}
if (position < buffer.length) {
// Shrink buffer.
byte[] newBuffer = new byte[position];
System.arraycopy(buffer, 0, newBuffer, 0, position);
buffer = newBuffer;
}
return buffer;
}
/** Reads the entire file into the byte array. The byte array must be big enough to hold the file's data.
* @param bytes the array to load the file into
* @param offset the offset to start writing bytes
* @param size the number of bytes to read, see {@link #length()}
* @return the number of read bytes */
public int readBytes (byte[] bytes, int offset, int size) {
InputStream input = read();
int position = 0;
try {
while (true) {
int count = input.read(bytes, offset + position, size - position);
if (count <= 0) break;
position += count;
}
} catch (IOException ex) {
throw new GdxRuntimeException("Error reading file: " + this, ex);
} finally {
try {
if (input != null) input.close();
} catch (IOException ignored) {
}
}
return position - offset;
}
public ByteBuffer map () {
throw new GdxRuntimeException("Cannot map files in GWT backend");
}
public ByteBuffer map (FileChannel.MapMode mode) {
throw new GdxRuntimeException("Cannot map files in GWT backend");
}
/** Returns a stream for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public OutputStream write (boolean append) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Reads the remaining bytes from the specified stream and writes them to this file. The stream is closed. Parent directories
* will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void write (InputStream input, boolean append) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Returns a writer for writing to this file using the default charset. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public Writer writer (boolean append) {
return writer(append, null);
}
/** Returns a writer for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param charset May be null to use the default charset.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public Writer writer (boolean append, String charset) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Writes the specified string to the file using the default charset. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeString (String string, boolean append) {
writeString(string, append, null);
}
/** Writes the specified string to the file as UTF-8. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param charset May be null to use the default charset.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeString (String string, boolean append, String charset) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Writes the specified bytes to the file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeBytes (byte[] bytes, boolean append) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Writes the specified bytes to the file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeBytes (byte[] bytes, int offset, int length, boolean append) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Returns the paths to the children of this directory. Returns an empty list if this file handle represents a file and not a
* directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath will return a zero length
* array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list () {
return preloader.list(file);
}
/** Returns the paths to the children of this directory that satisfy the specified filter. Returns an empty list if this file
* handle represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the
* classpath will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (FileFilter filter) {
return preloader.list(file, filter);
}
/** Returns the paths to the children of this directory that satisfy the specified filter. Returns an empty list if this file
* handle represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the
* classpath will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (FilenameFilter filter) {
return preloader.list(file, filter);
}
/** Returns the paths to the children of this directory with the specified suffix. Returns an empty list if this file handle
* represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath
* will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (String suffix) {
return preloader.list(file, suffix);
}
/** Returns true if this file is a directory. Always returns false for classpath files. On Android, an
* {@link FileType#Internal} handle to an empty directory will return false. On the desktop, an {@link FileType#Internal}
* handle to a directory on the classpath will return false. */
public boolean isDirectory () {
return preloader.isDirectory(file);
}
/** Returns a handle to the child with the specified name.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the child
* doesn't exist. */
public FileHandle child (String name) {
return new GwtFileHandle(preloader, (file.isEmpty() ? "" : (file + (file.endsWith("/") ? "" : "/"))) + name,
FileType.Internal);
}
public FileHandle parent () {
int index = file.lastIndexOf("/");
String dir = "";
if (index > 0) dir = file.substring(0, index);
return new GwtFileHandle(preloader, dir, type);
}
public FileHandle sibling (String name) {
return parent().child(fixSlashes(name));
}
/** @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public void mkdirs () {
throw new GdxRuntimeException("Cannot mkdirs with an internal file: " + file);
}
/** Returns true if the file exists. On Android, a {@link FileType#Classpath} or {@link FileType#Internal} handle to a
* directory will always return false. */
public boolean exists () {
return preloader.contains(file);
}
/** Deletes this file or empty directory and returns success. Will not delete a directory that has children.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public boolean delete () {
throw new GdxRuntimeException("Cannot delete an internal file: " + file);
}
/** Deletes this file or directory and all children, recursively.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public boolean deleteDirectory () {
throw new GdxRuntimeException("Cannot delete an internal file: " + file);
}
/** Copies this file or directory to the specified file or directory. If this handle is a file, then 1) if the destination is a
* file, it is overwritten, or 2) if the destination is a directory, this file is copied into it, or 3) if the destination
* doesn't exist, {@link #mkdirs()} is called on the destination's parent and this file is copied into it with a new name. If
* this handle is a directory, then 1) if the destination is a file, GdxRuntimeException is thrown, or 2) if the destination is
* a directory, this directory is copied into it recursively, overwriting existing files, or 3) if the destination doesn't
* exist, {@link #mkdirs()} is called on the destination and this directory is copied into it recursively.
* @throws GdxRuntimeException if the destination file handle is a {@link FileType#Classpath} or {@link FileType#Internal}
* file, or copying failed. */
public void copyTo (FileHandle dest) {
throw new GdxRuntimeException("Cannot copy to an internal file: " + dest);
}
/** Moves this file to the specified file, overwriting the file if it already exists.
* @throws GdxRuntimeException if the source or destination file handle is a {@link FileType#Classpath} or
* {@link FileType#Internal} file. */
public void moveTo (FileHandle dest) {
throw new GdxRuntimeException("Cannot move an internal file: " + file);
}
/** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be
* determined. */
public long length () {
return preloader.length(file);
}
/** Returns the last modified time in milliseconds for this file. Zero is returned if the file doesn't exist. Zero is returned
* for {@link FileType#Classpath} files. On Android, zero is returned for {@link FileType#Internal} files. On the desktop, zero
* is returned for {@link FileType#Internal} files on the classpath. */
public long lastModified () {
return 0;
}
public String toString () {
return file;
}
private static String fixSlashes (String path) {
path = path.replace('\\', '/');
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return path;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.gwt.preloader.Preloader;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class GwtFileHandle extends FileHandle {
public final Preloader preloader;
private final String file;
private final FileType type;
public GwtFileHandle (Preloader preloader, String fileName, FileType type) {
if (type != FileType.Internal && type != FileType.Classpath)
throw new GdxRuntimeException("FileType '" + type + "' Not supported in GWT backend");
this.preloader = preloader;
this.file = fixSlashes(fileName);
this.type = type;
}
public GwtFileHandle (String path) {
this.type = FileType.Internal;
this.preloader = ((GwtApplication)Gdx.app).getPreloader();
this.file = fixSlashes(path);
}
/** @return The full url to an asset, e.g. http://localhost:8080/assets/data/shotgun-e5f56587d6f025bff049632853ae4ff9.ogg */
public String getAssetUrl () {
return preloader.baseUrl + preloader.assetNames.get(file, file);
}
public String path () {
return file;
}
public String name () {
int index = file.lastIndexOf('/');
if (index < 0) return file;
return file.substring(index + 1);
}
public String extension () {
String name = name();
int dotIndex = name.lastIndexOf('.');
if (dotIndex == -1) return "";
return name.substring(dotIndex + 1);
}
public String nameWithoutExtension () {
String name = name();
int dotIndex = name.lastIndexOf('.');
if (dotIndex == -1) return name;
return name.substring(0, dotIndex);
}
/** @return the path and filename without the extension, e.g. dir/dir2/file.png -> dir/dir2/file */
public String pathWithoutExtension () {
String path = file;
int dotIndex = path.lastIndexOf('.');
if (dotIndex == -1) return path;
return path.substring(0, dotIndex);
}
public FileType type () {
return type;
}
/** Returns a java.io.File that represents this file handle. Note the returned file will only be usable for
* {@link FileType#Absolute} and {@link FileType#External} file handles. */
public File file () {
throw new GdxRuntimeException("file() not supported in GWT backend");
}
/** Returns a stream for reading this file as bytes.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public InputStream read () {
InputStream in = preloader.read(file);
if (in == null) throw new GdxRuntimeException(file + " does not exist");
return in;
}
/** Returns a buffered stream for reading this file as bytes.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedInputStream read (int bufferSize) {
return new BufferedInputStream(read(), bufferSize);
}
/** Returns a reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public Reader reader () {
return new InputStreamReader(read());
}
/** Returns a reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public Reader reader (String charset) {
try {
return new InputStreamReader(read(), charset);
} catch (UnsupportedEncodingException e) {
throw new GdxRuntimeException("Encoding '" + charset + "' not supported", e);
}
}
/** Returns a buffered reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize) {
return new BufferedReader(reader(), bufferSize);
}
/** Returns a buffered reader for reading this file as characters.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public BufferedReader reader (int bufferSize, String charset) {
return new BufferedReader(reader(charset), bufferSize);
}
/** Reads the entire file into a string using the platform's default charset.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString () {
return readString(null);
}
/** Reads the entire file into a string using the specified charset.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public String readString (String charset) {
if (preloader.isText(file)) return preloader.texts.get(file);
return new String(readBytes(), StandardCharsets.UTF_8);
}
/** Reads the entire file into a byte array.
* @throws GdxRuntimeException if the file handle represents a directory, doesn't exist, or could not be read. */
public byte[] readBytes () {
int length = (int)length();
if (length == 0) length = 512;
byte[] buffer = new byte[length];
int position = 0;
try (InputStream input = read()) {
while (true) {
int count = input.read(buffer, position, buffer.length - position);
if (count == -1) break;
position += count;
if (position == buffer.length) {
// Grow buffer.
byte[] newBuffer = new byte[buffer.length * 2];
System.arraycopy(buffer, 0, newBuffer, 0, position);
buffer = newBuffer;
}
}
} catch (IOException ex) {
throw new GdxRuntimeException("Error reading file: " + this, ex);
}
if (position < buffer.length) {
// Shrink buffer.
byte[] newBuffer = new byte[position];
System.arraycopy(buffer, 0, newBuffer, 0, position);
buffer = newBuffer;
}
return buffer;
}
/** Reads the entire file into the byte array. The byte array must be big enough to hold the file's data.
* @param bytes the array to load the file into
* @param offset the offset to start writing bytes
* @param size the number of bytes to read, see {@link #length()}
* @return the number of read bytes */
public int readBytes (byte[] bytes, int offset, int size) {
InputStream input = read();
int position = 0;
try {
while (true) {
int count = input.read(bytes, offset + position, size - position);
if (count <= 0) break;
position += count;
}
} catch (IOException ex) {
throw new GdxRuntimeException("Error reading file: " + this, ex);
} finally {
try {
if (input != null) input.close();
} catch (IOException ignored) {
}
}
return position - offset;
}
public ByteBuffer map () {
throw new GdxRuntimeException("Cannot map files in GWT backend");
}
public ByteBuffer map (FileChannel.MapMode mode) {
throw new GdxRuntimeException("Cannot map files in GWT backend");
}
/** Returns a stream for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public OutputStream write (boolean append) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Reads the remaining bytes from the specified stream and writes them to this file. The stream is closed. Parent directories
* will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void write (InputStream input, boolean append) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Returns a writer for writing to this file using the default charset. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public Writer writer (boolean append) {
return writer(append, null);
}
/** Returns a writer for writing to this file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param charset May be null to use the default charset.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public Writer writer (boolean append, String charset) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Writes the specified string to the file using the default charset. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeString (String string, boolean append) {
writeString(string, append, null);
}
/** Writes the specified string to the file as UTF-8. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @param charset May be null to use the default charset.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeString (String string, boolean append, String charset) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Writes the specified bytes to the file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeBytes (byte[] bytes, boolean append) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Writes the specified bytes to the file. Parent directories will be created if necessary.
* @param append If false, this file will be overwritten if it exists, otherwise it will be appended.
* @throws GdxRuntimeException if this file handle represents a directory, if it is a {@link FileType#Classpath} or
* {@link FileType#Internal} file, or if it could not be written. */
public void writeBytes (byte[] bytes, int offset, int length, boolean append) {
throw new GdxRuntimeException("Cannot write to files in GWT backend");
}
/** Returns the paths to the children of this directory. Returns an empty list if this file handle represents a file and not a
* directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath will return a zero length
* array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list () {
return preloader.list(file);
}
/** Returns the paths to the children of this directory that satisfy the specified filter. Returns an empty list if this file
* handle represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the
* classpath will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (FileFilter filter) {
return preloader.list(file, filter);
}
/** Returns the paths to the children of this directory that satisfy the specified filter. Returns an empty list if this file
* handle represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the
* classpath will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (FilenameFilter filter) {
return preloader.list(file, filter);
}
/** Returns the paths to the children of this directory with the specified suffix. Returns an empty list if this file handle
* represents a file and not a directory. On the desktop, an {@link FileType#Internal} handle to a directory on the classpath
* will return a zero length array.
* @throws GdxRuntimeException if this file is an {@link FileType#Classpath} file. */
public FileHandle[] list (String suffix) {
return preloader.list(file, suffix);
}
/** Returns true if this file is a directory. Always returns false for classpath files. On Android, an
* {@link FileType#Internal} handle to an empty directory will return false. On the desktop, an {@link FileType#Internal}
* handle to a directory on the classpath will return false. */
public boolean isDirectory () {
return preloader.isDirectory(file);
}
/** Returns a handle to the child with the specified name.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} and the child
* doesn't exist. */
public FileHandle child (String name) {
return new GwtFileHandle(preloader, (file.isEmpty() ? "" : (file + (file.endsWith("/") ? "" : "/"))) + name,
FileType.Internal);
}
public FileHandle parent () {
int index = file.lastIndexOf("/");
String dir = "";
if (index > 0) dir = file.substring(0, index);
return new GwtFileHandle(preloader, dir, type);
}
public FileHandle sibling (String name) {
return parent().child(fixSlashes(name));
}
/** @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public void mkdirs () {
throw new GdxRuntimeException("Cannot mkdirs with an internal file: " + file);
}
/** Returns true if the file exists. On Android, a {@link FileType#Classpath} or {@link FileType#Internal} handle to a
* directory will always return false. */
public boolean exists () {
return preloader.contains(file);
}
/** Deletes this file or empty directory and returns success. Will not delete a directory that has children.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public boolean delete () {
throw new GdxRuntimeException("Cannot delete an internal file: " + file);
}
/** Deletes this file or directory and all children, recursively.
* @throws GdxRuntimeException if this file handle is a {@link FileType#Classpath} or {@link FileType#Internal} file. */
public boolean deleteDirectory () {
throw new GdxRuntimeException("Cannot delete an internal file: " + file);
}
/** Copies this file or directory to the specified file or directory. If this handle is a file, then 1) if the destination is a
* file, it is overwritten, or 2) if the destination is a directory, this file is copied into it, or 3) if the destination
* doesn't exist, {@link #mkdirs()} is called on the destination's parent and this file is copied into it with a new name. If
* this handle is a directory, then 1) if the destination is a file, GdxRuntimeException is thrown, or 2) if the destination is
* a directory, this directory is copied into it recursively, overwriting existing files, or 3) if the destination doesn't
* exist, {@link #mkdirs()} is called on the destination and this directory is copied into it recursively.
* @throws GdxRuntimeException if the destination file handle is a {@link FileType#Classpath} or {@link FileType#Internal}
* file, or copying failed. */
public void copyTo (FileHandle dest) {
throw new GdxRuntimeException("Cannot copy to an internal file: " + dest);
}
/** Moves this file to the specified file, overwriting the file if it already exists.
* @throws GdxRuntimeException if the source or destination file handle is a {@link FileType#Classpath} or
* {@link FileType#Internal} file. */
public void moveTo (FileHandle dest) {
throw new GdxRuntimeException("Cannot move an internal file: " + file);
}
/** Returns the length in bytes of this file, or 0 if this file is a directory, does not exist, or the size cannot otherwise be
* determined. */
public long length () {
return preloader.length(file);
}
/** Returns the last modified time in milliseconds for this file. Zero is returned if the file doesn't exist. Zero is returned
* for {@link FileType#Classpath} files. On Android, zero is returned for {@link FileType#Internal} files. On the desktop, zero
* is returned for {@link FileType#Internal} files on the classpath. */
public long lastModified () {
return 0;
}
public String toString () {
return file;
}
private static String fixSlashes (String path) {
path = path.replace('\\', '/');
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return path;
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/TiledMapGroupLayerTest.java |
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader;
import com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.OrthoCamController;
import com.badlogic.gdx.utils.ScreenUtils;
public class TiledMapGroupLayerTest extends GdxTest {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private OrthoCamController cameraController;
private AssetManager assetManager;
private BitmapFont font;
private SpriteBatch batch;
String errorMessage;
private String fileName = "data/maps/tiled-groups/test.tmx";
@Override
public void create () {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, (w / h) * 10, 10);
camera.zoom = 2;
camera.update();
cameraController = new OrthoCamController(camera);
Gdx.input.setInputProcessor(cameraController);
font = new BitmapFont();
batch = new SpriteBatch();
AtlasTiledMapLoaderParameters params = new AtlasTiledMapLoaderParameters();
params.forceTextureFilters = true;
params.textureMinFilter = TextureFilter.Linear;
params.textureMagFilter = TextureFilter.Linear;
assetManager = new AssetManager();
assetManager.setErrorListener(new AssetErrorListener() {
@Override
public void error (AssetDescriptor asset, Throwable throwable) {
errorMessage = throwable.getMessage();
}
});
assetManager.setLoader(TiledMap.class, new AtlasTmxMapLoader(new InternalFileHandleResolver()));
assetManager.load(fileName, TiledMap.class);
}
@Override
public void render () {
ScreenUtils.clear(100f / 255f, 100f / 255f, 250f / 255f, 1f);
camera.update();
assetManager.update(16);
if (renderer == null && assetManager.isLoaded(fileName)) {
map = assetManager.get(fileName);
renderer = new OrthogonalTiledMapRenderer(map, 1f / 32f);
} else if (renderer != null) {
renderer.setView(camera);
renderer.render();
}
batch.begin();
if (errorMessage != null) {
font.draw(batch, "ERROR (OK if running in GWT): " + errorMessage, 10, 50);
System.out.println(errorMessage);
}
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
}
|
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader;
import com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.OrthoCamController;
import com.badlogic.gdx.utils.ScreenUtils;
public class TiledMapGroupLayerTest extends GdxTest {
private TiledMap map;
private TiledMapRenderer renderer;
private OrthographicCamera camera;
private OrthoCamController cameraController;
private AssetManager assetManager;
private BitmapFont font;
private SpriteBatch batch;
String errorMessage;
private String fileName = "data/maps/tiled-groups/test.tmx";
@Override
public void create () {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, (w / h) * 10, 10);
camera.zoom = 2;
camera.update();
cameraController = new OrthoCamController(camera);
Gdx.input.setInputProcessor(cameraController);
font = new BitmapFont();
batch = new SpriteBatch();
AtlasTiledMapLoaderParameters params = new AtlasTiledMapLoaderParameters();
params.forceTextureFilters = true;
params.textureMinFilter = TextureFilter.Linear;
params.textureMagFilter = TextureFilter.Linear;
assetManager = new AssetManager();
assetManager.setErrorListener(new AssetErrorListener() {
@Override
public void error (AssetDescriptor asset, Throwable throwable) {
errorMessage = throwable.getMessage();
}
});
assetManager.setLoader(TiledMap.class, new AtlasTmxMapLoader(new InternalFileHandleResolver()));
assetManager.load(fileName, TiledMap.class);
}
@Override
public void render () {
ScreenUtils.clear(100f / 255f, 100f / 255f, 250f / 255f, 1f);
camera.update();
assetManager.update(16);
if (renderer == null && assetManager.isLoaded(fileName)) {
map = assetManager.get(fileName);
renderer = new OrthogonalTiledMapRenderer(map, 1f / 32f);
} else if (renderer != null) {
renderer.setView(camera);
renderer.render();
}
batch.begin();
if (errorMessage != null) {
font.draw(batch, "ERROR (OK if running in GWT): " + errorMessage, 10, 50);
System.out.println(errorMessage);
}
font.draw(batch, "FPS: " + Gdx.graphics.getFramesPerSecond(), 10, 20);
batch.end();
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/graphics/TextureData.java |
package com.badlogic.gdx.graphics;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.glutils.FileTextureData;
import com.badlogic.gdx.graphics.glutils.MipMapGenerator;
/** Used by a {@link Texture} to load the pixel data. A TextureData can either return a {@link Pixmap} or upload the pixel data
* itself. It signals it's type via {@link #getType()} to the Texture that's using it. The Texture will then either invoke
* {@link #consumePixmap()} or {@link #consumeCustomData(int)}. These are the first methods to be called by Texture. After that
* the Texture will invoke the other methods to find out about the size of the image data, the format, whether mipmaps should be
* generated and whether the TextureData is able to manage the pixel data if the OpenGL ES context is lost.
* </p>
*
* In case the TextureData implementation has the type {@link TextureDataType#Custom}, the implementation has to generate the
* mipmaps itself if necessary. See {@link MipMapGenerator}.
* </p>
*
* Before a call to either {@link #consumePixmap()} or {@link #consumeCustomData(int)}, Texture will bind the OpenGL ES texture.
* </p>
*
* Look at {@link FileTextureData} for example implementations of this interface.
* @author mzechner */
public interface TextureData {
/** The type of this {@link TextureData}.
* @author mzechner */
public enum TextureDataType {
Pixmap, Custom
}
/** @return the {@link TextureDataType} */
public TextureDataType getType ();
/** @return whether the TextureData is prepared or not. */
public boolean isPrepared ();
/** Prepares the TextureData for a call to {@link #consumePixmap()} or {@link #consumeCustomData(int)}. This method can be
* called from a non OpenGL thread and should thus not interact with OpenGL. */
public void prepare ();
/** Returns the {@link Pixmap} for upload by Texture. A call to {@link #prepare()} must precede a call to this method. Any
* internal data structures created in {@link #prepare()} should be disposed of here.
*
* @return the pixmap. */
public Pixmap consumePixmap ();
/** @return whether the caller of {@link #consumePixmap()} should dispose the Pixmap returned by {@link #consumePixmap()} */
public boolean disposePixmap ();
/** Uploads the pixel data to the OpenGL ES texture. The caller must bind an OpenGL ES texture. A call to {@link #prepare()}
* must preceed a call to this method. Any internal data structures created in {@link #prepare()} should be disposed of
* here. */
public void consumeCustomData (int target);
/** @return the width of the pixel data */
public int getWidth ();
/** @return the height of the pixel data */
public int getHeight ();
/** @return the {@link Format} of the pixel data */
public Format getFormat ();
/** @return whether to generate mipmaps or not. */
public boolean useMipMaps ();
/** @return whether this implementation can cope with a EGL context loss. */
public boolean isManaged ();
/** Provides static method to instantiate the right implementation (Pixmap, ETC1, KTX).
* @author Vincent Bousquet */
public static class Factory {
public static TextureData loadFromFile (FileHandle file, boolean useMipMaps) {
return loadFromFile(file, null, useMipMaps);
}
public static TextureData loadFromFile (FileHandle file, Format format, boolean useMipMaps) {
if (file == null) return null;
return new FileTextureData(file, new Pixmap(file), format, useMipMaps);
}
}
}
|
package com.badlogic.gdx.graphics;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.glutils.FileTextureData;
import com.badlogic.gdx.graphics.glutils.MipMapGenerator;
/** Used by a {@link Texture} to load the pixel data. A TextureData can either return a {@link Pixmap} or upload the pixel data
* itself. It signals it's type via {@link #getType()} to the Texture that's using it. The Texture will then either invoke
* {@link #consumePixmap()} or {@link #consumeCustomData(int)}. These are the first methods to be called by Texture. After that
* the Texture will invoke the other methods to find out about the size of the image data, the format, whether mipmaps should be
* generated and whether the TextureData is able to manage the pixel data if the OpenGL ES context is lost.
* </p>
*
* In case the TextureData implementation has the type {@link TextureDataType#Custom}, the implementation has to generate the
* mipmaps itself if necessary. See {@link MipMapGenerator}.
* </p>
*
* Before a call to either {@link #consumePixmap()} or {@link #consumeCustomData(int)}, Texture will bind the OpenGL ES texture.
* </p>
*
* Look at {@link FileTextureData} for example implementations of this interface.
* @author mzechner */
public interface TextureData {
/** The type of this {@link TextureData}.
* @author mzechner */
public enum TextureDataType {
Pixmap, Custom
}
/** @return the {@link TextureDataType} */
public TextureDataType getType ();
/** @return whether the TextureData is prepared or not. */
public boolean isPrepared ();
/** Prepares the TextureData for a call to {@link #consumePixmap()} or {@link #consumeCustomData(int)}. This method can be
* called from a non OpenGL thread and should thus not interact with OpenGL. */
public void prepare ();
/** Returns the {@link Pixmap} for upload by Texture. A call to {@link #prepare()} must precede a call to this method. Any
* internal data structures created in {@link #prepare()} should be disposed of here.
*
* @return the pixmap. */
public Pixmap consumePixmap ();
/** @return whether the caller of {@link #consumePixmap()} should dispose the Pixmap returned by {@link #consumePixmap()} */
public boolean disposePixmap ();
/** Uploads the pixel data to the OpenGL ES texture. The caller must bind an OpenGL ES texture. A call to {@link #prepare()}
* must preceed a call to this method. Any internal data structures created in {@link #prepare()} should be disposed of
* here. */
public void consumeCustomData (int target);
/** @return the width of the pixel data */
public int getWidth ();
/** @return the height of the pixel data */
public int getHeight ();
/** @return the {@link Format} of the pixel data */
public Format getFormat ();
/** @return whether to generate mipmaps or not. */
public boolean useMipMaps ();
/** @return whether this implementation can cope with a EGL context loss. */
public boolean isManaged ();
/** Provides static method to instantiate the right implementation (Pixmap, ETC1, KTX).
* @author Vincent Bousquet */
public static class Factory {
public static TextureData loadFromFile (FileHandle file, boolean useMipMaps) {
return loadFromFile(file, null, useMipMaps);
}
public static TextureData loadFromFile (FileHandle file, Format format, boolean useMipMaps) {
if (file == null) return null;
return new FileTextureData(file, new Pixmap(file), format, useMipMaps);
}
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/net/PingPongSocketExample.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net.Protocol;
import com.badlogic.gdx.net.ServerSocket;
import com.badlogic.gdx.net.ServerSocketHints;
import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.net.SocketHints;
import com.badlogic.gdx.tests.utils.GdxTest;
/** Demonstrates how to do very simple socket programming. Implements a classic PING-PONG sequence, client connects to server,
* sends message, server sends message back to client. Both client and server run locally. We quit as soon as the client received
* the PONG message from the server. This example won't work in HTML. Messages are delimited by the new line character, so we can
* use a {@link BufferedReader}.
* @author badlogic */
public class PingPongSocketExample extends GdxTest {
@Override
public void create () {
// setup a server thread where we wait for incoming connections
// to the server
new Thread(new Runnable() {
@Override
public void run () {
ServerSocketHints hints = new ServerSocketHints();
ServerSocket server = Gdx.net.newServerSocket(Protocol.TCP, "localhost", 9999, hints);
// wait for the next client connection
Socket client = server.accept(null);
// read message and send it back
try {
String message = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
Gdx.app.log("PingPongSocketExample", "got client message: " + message);
client.getOutputStream().write("PONG\n".getBytes());
} catch (IOException e) {
Gdx.app.log("PingPongSocketExample", "an error occured", e);
}
}
}).start();
// create the client send a message, then wait for the
// server to reply
SocketHints hints = new SocketHints();
Socket client = Gdx.net.newClientSocket(Protocol.TCP, "localhost", 9999, hints);
try {
client.getOutputStream().write("PING\n".getBytes());
String response = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
Gdx.app.log("PingPongSocketExample", "got server message: " + response);
} catch (IOException e) {
Gdx.app.log("PingPongSocketExample", "an error occured", e);
}
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net.Protocol;
import com.badlogic.gdx.net.ServerSocket;
import com.badlogic.gdx.net.ServerSocketHints;
import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.net.SocketHints;
import com.badlogic.gdx.tests.utils.GdxTest;
/** Demonstrates how to do very simple socket programming. Implements a classic PING-PONG sequence, client connects to server,
* sends message, server sends message back to client. Both client and server run locally. We quit as soon as the client received
* the PONG message from the server. This example won't work in HTML. Messages are delimited by the new line character, so we can
* use a {@link BufferedReader}.
* @author badlogic */
public class PingPongSocketExample extends GdxTest {
@Override
public void create () {
// setup a server thread where we wait for incoming connections
// to the server
new Thread(new Runnable() {
@Override
public void run () {
ServerSocketHints hints = new ServerSocketHints();
ServerSocket server = Gdx.net.newServerSocket(Protocol.TCP, "localhost", 9999, hints);
// wait for the next client connection
Socket client = server.accept(null);
// read message and send it back
try {
String message = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
Gdx.app.log("PingPongSocketExample", "got client message: " + message);
client.getOutputStream().write("PONG\n".getBytes());
} catch (IOException e) {
Gdx.app.log("PingPongSocketExample", "an error occured", e);
}
}
}).start();
// create the client send a message, then wait for the
// server to reply
SocketHints hints = new SocketHints();
Socket client = Gdx.net.newClientSocket(Protocol.TCP, "localhost", 9999, hints);
try {
client.getOutputStream().write("PING\n".getBytes());
String response = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
Gdx.app.log("PingPongSocketExample", "got server message: " + response);
} catch (IOException e) {
Gdx.app.log("PingPongSocketExample", "an error occured", e);
}
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./tests/gdx-tests/src/com/badlogic/gdx/tests/TimerTest.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
public class TimerTest extends GdxTest {
@Override
public void create () {
Timer timer = new Timer();
Task task = timer.scheduleTask(new Task() {
@Override
public void run () {
Gdx.app.log("TimerTest", "ping");
}
}, 1, 1);
Gdx.app.log("TimerTest", "is task scheduled: " + String.valueOf(task.isScheduled()));
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
public class TimerTest extends GdxTest {
@Override
public void create () {
Timer timer = new Timer();
Task task = timer.scheduleTask(new Task() {
@Override
public void run () {
Gdx.app.log("TimerTest", "ping");
}
}, 1, 1);
Gdx.app.log("TimerTest", "is task scheduled: " + String.valueOf(task.isScheduled()));
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-bullet/jni/swig-src/dynamics/com/badlogic/gdx/physics/bullet/dynamics/btMultiBodyFloatData.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btMultiBodyFloatData extends BulletBase {
private long swigCPtr;
protected btMultiBodyFloatData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btMultiBodyFloatData, normally you should not need this constructor it's intended for low-level usage. */
public btMultiBodyFloatData (long cPtr, boolean cMemoryOwn) {
this("btMultiBodyFloatData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btMultiBodyFloatData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btMultiBodyFloatData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setBaseName (String value) {
DynamicsJNI.btMultiBodyFloatData_baseName_set(swigCPtr, this, value);
}
public String getBaseName () {
return DynamicsJNI.btMultiBodyFloatData_baseName_get(swigCPtr, this);
}
public void setLinks (btMultiBodyLinkFloatData value) {
DynamicsJNI.btMultiBodyFloatData_links_set(swigCPtr, this, btMultiBodyLinkFloatData.getCPtr(value), value);
}
public btMultiBodyLinkFloatData getLinks () {
long cPtr = DynamicsJNI.btMultiBodyFloatData_links_get(swigCPtr, this);
return (cPtr == 0) ? null : new btMultiBodyLinkFloatData(cPtr, false);
}
public void setBaseCollider (btCollisionObjectFloatData value) {
DynamicsJNI.btMultiBodyFloatData_baseCollider_set(swigCPtr, this, btCollisionObjectFloatData.getCPtr(value), value);
}
public btCollisionObjectFloatData getBaseCollider () {
long cPtr = DynamicsJNI.btMultiBodyFloatData_baseCollider_get(swigCPtr, this);
return (cPtr == 0) ? null : new btCollisionObjectFloatData(cPtr, false);
}
public void setBaseWorldTransform (btTransformFloatData value) {
DynamicsJNI.btMultiBodyFloatData_baseWorldTransform_set(swigCPtr, this, btTransformFloatData.getCPtr(value), value);
}
public btTransformFloatData getBaseWorldTransform () {
long cPtr = DynamicsJNI.btMultiBodyFloatData_baseWorldTransform_get(swigCPtr, this);
return (cPtr == 0) ? null : new btTransformFloatData(cPtr, false);
}
public void setBaseInertia (btVector3FloatData value) {
DynamicsJNI.btMultiBodyFloatData_baseInertia_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getBaseInertia () {
long cPtr = DynamicsJNI.btMultiBodyFloatData_baseInertia_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setBaseMass (float value) {
DynamicsJNI.btMultiBodyFloatData_baseMass_set(swigCPtr, this, value);
}
public float getBaseMass () {
return DynamicsJNI.btMultiBodyFloatData_baseMass_get(swigCPtr, this);
}
public void setNumLinks (int value) {
DynamicsJNI.btMultiBodyFloatData_numLinks_set(swigCPtr, this, value);
}
public int getNumLinks () {
return DynamicsJNI.btMultiBodyFloatData_numLinks_get(swigCPtr, this);
}
public btMultiBodyFloatData () {
this(DynamicsJNI.new_btMultiBodyFloatData(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.dynamics;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
public class btMultiBodyFloatData extends BulletBase {
private long swigCPtr;
protected btMultiBodyFloatData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btMultiBodyFloatData, normally you should not need this constructor it's intended for low-level usage. */
public btMultiBodyFloatData (long cPtr, boolean cMemoryOwn) {
this("btMultiBodyFloatData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (btMultiBodyFloatData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
DynamicsJNI.delete_btMultiBodyFloatData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setBaseName (String value) {
DynamicsJNI.btMultiBodyFloatData_baseName_set(swigCPtr, this, value);
}
public String getBaseName () {
return DynamicsJNI.btMultiBodyFloatData_baseName_get(swigCPtr, this);
}
public void setLinks (btMultiBodyLinkFloatData value) {
DynamicsJNI.btMultiBodyFloatData_links_set(swigCPtr, this, btMultiBodyLinkFloatData.getCPtr(value), value);
}
public btMultiBodyLinkFloatData getLinks () {
long cPtr = DynamicsJNI.btMultiBodyFloatData_links_get(swigCPtr, this);
return (cPtr == 0) ? null : new btMultiBodyLinkFloatData(cPtr, false);
}
public void setBaseCollider (btCollisionObjectFloatData value) {
DynamicsJNI.btMultiBodyFloatData_baseCollider_set(swigCPtr, this, btCollisionObjectFloatData.getCPtr(value), value);
}
public btCollisionObjectFloatData getBaseCollider () {
long cPtr = DynamicsJNI.btMultiBodyFloatData_baseCollider_get(swigCPtr, this);
return (cPtr == 0) ? null : new btCollisionObjectFloatData(cPtr, false);
}
public void setBaseWorldTransform (btTransformFloatData value) {
DynamicsJNI.btMultiBodyFloatData_baseWorldTransform_set(swigCPtr, this, btTransformFloatData.getCPtr(value), value);
}
public btTransformFloatData getBaseWorldTransform () {
long cPtr = DynamicsJNI.btMultiBodyFloatData_baseWorldTransform_get(swigCPtr, this);
return (cPtr == 0) ? null : new btTransformFloatData(cPtr, false);
}
public void setBaseInertia (btVector3FloatData value) {
DynamicsJNI.btMultiBodyFloatData_baseInertia_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getBaseInertia () {
long cPtr = DynamicsJNI.btMultiBodyFloatData_baseInertia_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setBaseMass (float value) {
DynamicsJNI.btMultiBodyFloatData_baseMass_set(swigCPtr, this, value);
}
public float getBaseMass () {
return DynamicsJNI.btMultiBodyFloatData_baseMass_get(swigCPtr, this);
}
public void setNumLinks (int value) {
DynamicsJNI.btMultiBodyFloatData_numLinks_set(swigCPtr, this, value);
}
public int getNumLinks () {
return DynamicsJNI.btMultiBodyFloatData_numLinks_get(swigCPtr, this);
}
public btMultiBodyFloatData () {
this(DynamicsJNI.new_btMultiBodyFloatData(), true);
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/SwingLwjglTest.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests.lwjgl;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglAWTCanvas;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.tests.MusicTest;
import com.badlogic.gdx.tests.UITest;
/** Demonstrates how to use LwjglAWTCanvas to have multiple GL widgets in a Swing application.
* @author mzechner */
public class SwingLwjglTest extends JFrame {
LwjglAWTCanvas canvas1;
LwjglAWTCanvas canvas2;
LwjglAWTCanvas canvas3;
public SwingLwjglTest () {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container container = getContentPane();
canvas1 = new LwjglAWTCanvas(new MusicTest());
canvas2 = new LwjglAWTCanvas(new UITest(), canvas1);
canvas3 = new LwjglAWTCanvas(new WindowCreator(), canvas1);
canvas1.getCanvas().setSize(200, 480);
canvas2.getCanvas().setSize(200, 480);
canvas3.getCanvas().setSize(200, 480);
container.add(canvas1.getCanvas(), BorderLayout.LINE_START);
container.add(canvas2.getCanvas(), BorderLayout.CENTER);
container.add(canvas3.getCanvas(), BorderLayout.LINE_END);
pack();
setVisible(true);
setSize(800, 480);
}
class WindowCreator extends ApplicationAdapter {
SpriteBatch batch;
BitmapFont font;
@Override
public void create () {
batch = new SpriteBatch();
font = new BitmapFont();
}
@Override
public void dispose () {
font.dispose();
batch.dispose();
}
@Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Click to create a new window", 10, 100);
batch.end();
if (Gdx.input.justTouched()) {
createWindow();
}
}
private void createWindow () {
JFrame window = new JFrame();
LwjglAWTCanvas canvas = new LwjglAWTCanvas(new UITest(), canvas1);
window.getContentPane().add(canvas.getCanvas(), BorderLayout.CENTER);
window.pack();
window.setVisible(true);
window.setSize(200, 200);
}
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run () {
new SwingLwjglTest();
}
});
}
@Override
public void dispose () {
canvas3.stop();
canvas2.stop();
canvas1.stop();
super.dispose();
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.tests.lwjgl;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglAWTCanvas;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.tests.MusicTest;
import com.badlogic.gdx.tests.UITest;
/** Demonstrates how to use LwjglAWTCanvas to have multiple GL widgets in a Swing application.
* @author mzechner */
public class SwingLwjglTest extends JFrame {
LwjglAWTCanvas canvas1;
LwjglAWTCanvas canvas2;
LwjglAWTCanvas canvas3;
public SwingLwjglTest () {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container container = getContentPane();
canvas1 = new LwjglAWTCanvas(new MusicTest());
canvas2 = new LwjglAWTCanvas(new UITest(), canvas1);
canvas3 = new LwjglAWTCanvas(new WindowCreator(), canvas1);
canvas1.getCanvas().setSize(200, 480);
canvas2.getCanvas().setSize(200, 480);
canvas3.getCanvas().setSize(200, 480);
container.add(canvas1.getCanvas(), BorderLayout.LINE_START);
container.add(canvas2.getCanvas(), BorderLayout.CENTER);
container.add(canvas3.getCanvas(), BorderLayout.LINE_END);
pack();
setVisible(true);
setSize(800, 480);
}
class WindowCreator extends ApplicationAdapter {
SpriteBatch batch;
BitmapFont font;
@Override
public void create () {
batch = new SpriteBatch();
font = new BitmapFont();
}
@Override
public void dispose () {
font.dispose();
batch.dispose();
}
@Override
public void render () {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Click to create a new window", 10, 100);
batch.end();
if (Gdx.input.justTouched()) {
createWindow();
}
}
private void createWindow () {
JFrame window = new JFrame();
LwjglAWTCanvas canvas = new LwjglAWTCanvas(new UITest(), canvas1);
window.getContentPane().add(canvas.getCanvas(), BorderLayout.CENTER);
window.pack();
window.setVisible(true);
window.setSize(200, 200);
}
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run () {
new SwingLwjglTest();
}
});
}
@Override
public void dispose () {
canvas3.stop();
canvas2.stop();
canvas1.stop();
super.dispose();
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-bullet/jni/swig-src/softbody/com/badlogic/gdx/physics/bullet/softbody/SoftBodyFaceData.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.softbody;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
import com.badlogic.gdx.physics.bullet.dynamics.*;
public class SoftBodyFaceData extends BulletBase {
private long swigCPtr;
protected SoftBodyFaceData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new SoftBodyFaceData, normally you should not need this constructor it's intended for low-level usage. */
public SoftBodyFaceData (long cPtr, boolean cMemoryOwn) {
this("SoftBodyFaceData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (SoftBodyFaceData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
SoftbodyJNI.delete_SoftBodyFaceData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setNormal (btVector3FloatData value) {
SoftbodyJNI.SoftBodyFaceData_normal_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getNormal () {
long cPtr = SoftbodyJNI.SoftBodyFaceData_normal_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setMaterial (SoftBodyMaterialData value) {
SoftbodyJNI.SoftBodyFaceData_material_set(swigCPtr, this, SoftBodyMaterialData.getCPtr(value), value);
}
public SoftBodyMaterialData getMaterial () {
long cPtr = SoftbodyJNI.SoftBodyFaceData_material_get(swigCPtr, this);
return (cPtr == 0) ? null : new SoftBodyMaterialData(cPtr, false);
}
public void setNodeIndices (int[] value) {
SoftbodyJNI.SoftBodyFaceData_nodeIndices_set(swigCPtr, this, value);
}
public int[] getNodeIndices () {
return SoftbodyJNI.SoftBodyFaceData_nodeIndices_get(swigCPtr, this);
}
public void setRestArea (float value) {
SoftbodyJNI.SoftBodyFaceData_restArea_set(swigCPtr, this, value);
}
public float getRestArea () {
return SoftbodyJNI.SoftBodyFaceData_restArea_get(swigCPtr, this);
}
public SoftBodyFaceData () {
this(SoftbodyJNI.new_SoftBodyFaceData(), true);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.softbody;
import com.badlogic.gdx.physics.bullet.BulletBase;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.physics.bullet.collision.*;
import com.badlogic.gdx.physics.bullet.dynamics.*;
public class SoftBodyFaceData extends BulletBase {
private long swigCPtr;
protected SoftBodyFaceData (final String className, long cPtr, boolean cMemoryOwn) {
super(className, cPtr, cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new SoftBodyFaceData, normally you should not need this constructor it's intended for low-level usage. */
public SoftBodyFaceData (long cPtr, boolean cMemoryOwn) {
this("SoftBodyFaceData", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(swigCPtr = cPtr, cMemoryOwn);
}
public static long getCPtr (SoftBodyFaceData obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
SoftbodyJNI.delete_SoftBodyFaceData(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setNormal (btVector3FloatData value) {
SoftbodyJNI.SoftBodyFaceData_normal_set(swigCPtr, this, btVector3FloatData.getCPtr(value), value);
}
public btVector3FloatData getNormal () {
long cPtr = SoftbodyJNI.SoftBodyFaceData_normal_get(swigCPtr, this);
return (cPtr == 0) ? null : new btVector3FloatData(cPtr, false);
}
public void setMaterial (SoftBodyMaterialData value) {
SoftbodyJNI.SoftBodyFaceData_material_set(swigCPtr, this, SoftBodyMaterialData.getCPtr(value), value);
}
public SoftBodyMaterialData getMaterial () {
long cPtr = SoftbodyJNI.SoftBodyFaceData_material_get(swigCPtr, this);
return (cPtr == 0) ? null : new SoftBodyMaterialData(cPtr, false);
}
public void setNodeIndices (int[] value) {
SoftbodyJNI.SoftBodyFaceData_nodeIndices_set(swigCPtr, this, value);
}
public int[] getNodeIndices () {
return SoftbodyJNI.SoftBodyFaceData_nodeIndices_get(swigCPtr, this);
}
public void setRestArea (float value) {
SoftbodyJNI.SoftBodyFaceData_restArea_set(swigCPtr, this, value);
}
public float getRestArea () {
return SoftbodyJNI.SoftBodyFaceData_restArea_get(swigCPtr, this);
}
public SoftBodyFaceData () {
this(SoftbodyJNI.new_SoftBodyFaceData(), true);
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/btSimpleBroadphase.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btSimpleBroadphase extends btBroadphaseInterface {
private long swigCPtr;
protected btSimpleBroadphase (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSimpleBroadphase_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSimpleBroadphase, normally you should not need this constructor it's intended for low-level usage. */
public btSimpleBroadphase (long cPtr, boolean cMemoryOwn) {
this("btSimpleBroadphase", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSimpleBroadphase_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSimpleBroadphase obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSimpleBroadphase(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btSimpleBroadphase (int maxProxies, btOverlappingPairCache overlappingPairCache) {
this(CollisionJNI.new_btSimpleBroadphase__SWIG_0(maxProxies, btOverlappingPairCache.getCPtr(overlappingPairCache),
overlappingPairCache), true);
}
public btSimpleBroadphase (int maxProxies) {
this(CollisionJNI.new_btSimpleBroadphase__SWIG_1(maxProxies), true);
}
public btSimpleBroadphase () {
this(CollisionJNI.new_btSimpleBroadphase__SWIG_2(), true);
}
public static boolean aabbOverlap (btSimpleBroadphaseProxy proxy0, btSimpleBroadphaseProxy proxy1) {
return CollisionJNI.btSimpleBroadphase_aabbOverlap(btSimpleBroadphaseProxy.getCPtr(proxy0), proxy0,
btSimpleBroadphaseProxy.getCPtr(proxy1), proxy1);
}
public void rayTest (Vector3 rayFrom, Vector3 rayTo, btBroadphaseRayCallback rayCallback, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btSimpleBroadphase_rayTest__SWIG_0(swigCPtr, this, rayFrom, rayTo,
btBroadphaseRayCallback.getCPtr(rayCallback), rayCallback, aabbMin, aabbMax);
}
public void rayTest (Vector3 rayFrom, Vector3 rayTo, btBroadphaseRayCallback rayCallback, Vector3 aabbMin) {
CollisionJNI.btSimpleBroadphase_rayTest__SWIG_1(swigCPtr, this, rayFrom, rayTo,
btBroadphaseRayCallback.getCPtr(rayCallback), rayCallback, aabbMin);
}
public void rayTest (Vector3 rayFrom, Vector3 rayTo, btBroadphaseRayCallback rayCallback) {
CollisionJNI.btSimpleBroadphase_rayTest__SWIG_2(swigCPtr, this, rayFrom, rayTo,
btBroadphaseRayCallback.getCPtr(rayCallback), rayCallback);
}
public boolean testAabbOverlap (btBroadphaseProxy proxy0, btBroadphaseProxy proxy1) {
return CollisionJNI.btSimpleBroadphase_testAabbOverlap(swigCPtr, this, btBroadphaseProxy.getCPtr(proxy0), proxy0,
btBroadphaseProxy.getCPtr(proxy1), proxy1);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class btSimpleBroadphase extends btBroadphaseInterface {
private long swigCPtr;
protected btSimpleBroadphase (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.btSimpleBroadphase_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new btSimpleBroadphase, normally you should not need this constructor it's intended for low-level usage. */
public btSimpleBroadphase (long cPtr, boolean cMemoryOwn) {
this("btSimpleBroadphase", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.btSimpleBroadphase_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (btSimpleBroadphase obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_btSimpleBroadphase(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public btSimpleBroadphase (int maxProxies, btOverlappingPairCache overlappingPairCache) {
this(CollisionJNI.new_btSimpleBroadphase__SWIG_0(maxProxies, btOverlappingPairCache.getCPtr(overlappingPairCache),
overlappingPairCache), true);
}
public btSimpleBroadphase (int maxProxies) {
this(CollisionJNI.new_btSimpleBroadphase__SWIG_1(maxProxies), true);
}
public btSimpleBroadphase () {
this(CollisionJNI.new_btSimpleBroadphase__SWIG_2(), true);
}
public static boolean aabbOverlap (btSimpleBroadphaseProxy proxy0, btSimpleBroadphaseProxy proxy1) {
return CollisionJNI.btSimpleBroadphase_aabbOverlap(btSimpleBroadphaseProxy.getCPtr(proxy0), proxy0,
btSimpleBroadphaseProxy.getCPtr(proxy1), proxy1);
}
public void rayTest (Vector3 rayFrom, Vector3 rayTo, btBroadphaseRayCallback rayCallback, Vector3 aabbMin, Vector3 aabbMax) {
CollisionJNI.btSimpleBroadphase_rayTest__SWIG_0(swigCPtr, this, rayFrom, rayTo,
btBroadphaseRayCallback.getCPtr(rayCallback), rayCallback, aabbMin, aabbMax);
}
public void rayTest (Vector3 rayFrom, Vector3 rayTo, btBroadphaseRayCallback rayCallback, Vector3 aabbMin) {
CollisionJNI.btSimpleBroadphase_rayTest__SWIG_1(swigCPtr, this, rayFrom, rayTo,
btBroadphaseRayCallback.getCPtr(rayCallback), rayCallback, aabbMin);
}
public void rayTest (Vector3 rayFrom, Vector3 rayTo, btBroadphaseRayCallback rayCallback) {
CollisionJNI.btSimpleBroadphase_rayTest__SWIG_2(swigCPtr, this, rayFrom, rayTo,
btBroadphaseRayCallback.getCPtr(rayCallback), rayCallback);
}
public boolean testAabbOverlap (btBroadphaseProxy proxy0, btBroadphaseProxy proxy1) {
return CollisionJNI.btSimpleBroadphase_testAabbOverlap(swigCPtr, this, btBroadphaseProxy.getCPtr(proxy0), proxy0,
btBroadphaseProxy.getCPtr(proxy1), proxy1);
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./gdx/src/com/badlogic/gdx/Screen.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx;
/**
* <p>
* Represents one of many application screens, such as a main menu, a settings menu, the game screen and so on.
* </p>
* <p>
* Note that {@link #dispose()} is not called automatically.
* </p>
* @see Game */
public interface Screen {
/** Called when this screen becomes the current screen for a {@link Game}. */
public void show ();
/** Called when the screen should render itself.
* @param delta The time in seconds since the last render. */
public void render (float delta);
/** @see ApplicationListener#resize(int, int) */
public void resize (int width, int height);
/** @see ApplicationListener#pause() */
public void pause ();
/** @see ApplicationListener#resume() */
public void resume ();
/** Called when this screen is no longer the current screen for a {@link Game}. */
public void hide ();
/** Called when this screen should release all resources. */
public void dispose ();
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx;
/**
* <p>
* Represents one of many application screens, such as a main menu, a settings menu, the game screen and so on.
* </p>
* <p>
* Note that {@link #dispose()} is not called automatically.
* </p>
* @see Game */
public interface Screen {
/** Called when this screen becomes the current screen for a {@link Game}. */
public void show ();
/** Called when the screen should render itself.
* @param delta The time in seconds since the last render. */
public void render (float delta);
/** @see ApplicationListener#resize(int, int) */
public void resize (int width, int height);
/** @see ApplicationListener#pause() */
public void pause ();
/** @see ApplicationListener#resume() */
public void resume ();
/** Called when this screen is no longer the current screen for a {@link Game}. */
public void hide ();
/** Called when this screen should release all resources. */
public void dispose ();
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-bullet/jni/swig-src/collision/com/badlogic/gdx/physics/bullet/collision/ClosestNotMeConvexResultCallback.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class ClosestNotMeConvexResultCallback extends ClosestConvexResultCallback {
private long swigCPtr;
protected ClosestNotMeConvexResultCallback (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.ClosestNotMeConvexResultCallback_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new ClosestNotMeConvexResultCallback, normally you should not need this constructor it's intended for low-level
* usage. */
public ClosestNotMeConvexResultCallback (long cPtr, boolean cMemoryOwn) {
this("ClosestNotMeConvexResultCallback", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.ClosestNotMeConvexResultCallback_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (ClosestNotMeConvexResultCallback obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_ClosestNotMeConvexResultCallback(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setMe (btCollisionObject value) {
CollisionJNI.ClosestNotMeConvexResultCallback_me_set(swigCPtr, this, btCollisionObject.getCPtr(value), value);
}
public btCollisionObject getMe () {
return btCollisionObject.getInstance(CollisionJNI.ClosestNotMeConvexResultCallback_me_get(swigCPtr, this), false);
}
public void setAllowedPenetration (float value) {
CollisionJNI.ClosestNotMeConvexResultCallback_allowedPenetration_set(swigCPtr, this, value);
}
public float getAllowedPenetration () {
return CollisionJNI.ClosestNotMeConvexResultCallback_allowedPenetration_get(swigCPtr, this);
}
public ClosestNotMeConvexResultCallback (btCollisionObject me, Vector3 fromA, Vector3 toA) {
this(CollisionJNI.new_ClosestNotMeConvexResultCallback(btCollisionObject.getCPtr(me), me, fromA, toA), true);
}
public boolean needsCollision (btBroadphaseProxy proxy0) {
return CollisionJNI.ClosestNotMeConvexResultCallback_needsCollision(swigCPtr, this, btBroadphaseProxy.getCPtr(proxy0),
proxy0);
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.collision;
import com.badlogic.gdx.physics.bullet.linearmath.*;
import com.badlogic.gdx.math.Vector3;
public class ClosestNotMeConvexResultCallback extends ClosestConvexResultCallback {
private long swigCPtr;
protected ClosestNotMeConvexResultCallback (final String className, long cPtr, boolean cMemoryOwn) {
super(className, CollisionJNI.ClosestNotMeConvexResultCallback_SWIGUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/** Construct a new ClosestNotMeConvexResultCallback, normally you should not need this constructor it's intended for low-level
* usage. */
public ClosestNotMeConvexResultCallback (long cPtr, boolean cMemoryOwn) {
this("ClosestNotMeConvexResultCallback", cPtr, cMemoryOwn);
construct();
}
@Override
protected void reset (long cPtr, boolean cMemoryOwn) {
if (!destroyed) destroy();
super.reset(CollisionJNI.ClosestNotMeConvexResultCallback_SWIGUpcast(swigCPtr = cPtr), cMemoryOwn);
}
public static long getCPtr (ClosestNotMeConvexResultCallback obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
@Override
protected void finalize () throws Throwable {
if (!destroyed) destroy();
super.finalize();
}
@Override
protected synchronized void delete () {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
CollisionJNI.delete_ClosestNotMeConvexResultCallback(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public void setMe (btCollisionObject value) {
CollisionJNI.ClosestNotMeConvexResultCallback_me_set(swigCPtr, this, btCollisionObject.getCPtr(value), value);
}
public btCollisionObject getMe () {
return btCollisionObject.getInstance(CollisionJNI.ClosestNotMeConvexResultCallback_me_get(swigCPtr, this), false);
}
public void setAllowedPenetration (float value) {
CollisionJNI.ClosestNotMeConvexResultCallback_allowedPenetration_set(swigCPtr, this, value);
}
public float getAllowedPenetration () {
return CollisionJNI.ClosestNotMeConvexResultCallback_allowedPenetration_get(swigCPtr, this);
}
public ClosestNotMeConvexResultCallback (btCollisionObject me, Vector3 fromA, Vector3 toA) {
this(CollisionJNI.new_ClosestNotMeConvexResultCallback(btCollisionObject.getCPtr(me), me, fromA, toA), true);
}
public boolean needsCollision (btBroadphaseProxy proxy0) {
return CollisionJNI.ClosestNotMeConvexResultCallback_needsCollision(swigCPtr, this, btBroadphaseProxy.getCPtr(proxy0),
proxy0);
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./gdx/test/com/badlogic/gdx/utils/FlushablePoolTest.java |
package com.badlogic.gdx.utils;
import org.junit.Test;
import static org.junit.Assert.*;
public class FlushablePoolTest {
@Test
public void initializeFlushablePoolTest1 () {
FlushablePoolClass flushablePool = new FlushablePoolClass();
assertEquals(0, flushablePool.getFree());
assertEquals(Integer.MAX_VALUE, flushablePool.max);
}
@Test
public void initializeFlushablePoolTest2 () {
FlushablePoolClass flushablePool = new FlushablePoolClass(10);
assertEquals(0, flushablePool.getFree());
assertEquals(Integer.MAX_VALUE, flushablePool.max);
}
@Test
public void initializeFlushablePoolTest3 () {
FlushablePoolClass flushablePool = new FlushablePoolClass(10, 10);
assertEquals(0, flushablePool.getFree());
assertEquals(10, flushablePool.max);
}
@Test
public void obtainTest () {
FlushablePoolClass flushablePool = new FlushablePoolClass(10, 10);
flushablePool.newObject();
assertEquals(0, flushablePool.obtained.size);
flushablePool.obtain();
assertEquals(1, flushablePool.obtained.size);
flushablePool.flush();
assertEquals(0, flushablePool.obtained.size);
}
@Test
public void flushTest () {
FlushablePoolClass flushablePool = new FlushablePoolClass(10, 10);
flushablePool.newObject();
flushablePool.obtain();
assertEquals(1, flushablePool.obtained.size);
flushablePool.flush();
assertEquals(0, flushablePool.obtained.size);
}
@Test
public void freeTest () {
// Create the flushable pool.
FlushablePoolClass flushablePool = new FlushablePoolClass(10, 10);
flushablePool.newObject();
flushablePool.newObject();
// Obtain the elements.
String element1 = flushablePool.obtain();
String element2 = flushablePool.obtain();
// Test preconditions.
assertTrue(flushablePool.obtained.contains(element1, true));
assertTrue(flushablePool.obtained.contains(element2, true));
// Free element and check containment.
flushablePool.free(element2);
assertTrue(flushablePool.obtained.contains(element1, true));
assertFalse(flushablePool.obtained.contains(element2, true));
}
@Test
public void freeAllTest () {
// Create the flushable pool.
FlushablePoolClass flushablePool = new FlushablePoolClass(5, 5);
flushablePool.newObject();
flushablePool.newObject();
// Obtain the elements.
final String element1 = flushablePool.obtain();
final String element2 = flushablePool.obtain();
// Create array with elements.
Array<String> elementArray = new Array<>();
elementArray.add(element1);
elementArray.add(element2);
// Test preconditions.
assertTrue(flushablePool.obtained.contains(element1, true));
assertTrue(flushablePool.obtained.contains(element2, true));
// Free elements and check containment.
flushablePool.freeAll(elementArray);
assertFalse(flushablePool.obtained.contains(element1, true));
assertFalse(flushablePool.obtained.contains(element2, true));
}
/** Test implementation class of FlushablePool. */
private class FlushablePoolClass extends FlushablePool<String> {
FlushablePoolClass () {
super();
}
FlushablePoolClass (int initialCapacity) {
super(initialCapacity);
}
FlushablePoolClass (int initialCapacity, int max) {
super(initialCapacity, max);
}
@Override
protected String newObject () {
return Integer.toString(getFree());
}
}
}
|
package com.badlogic.gdx.utils;
import org.junit.Test;
import static org.junit.Assert.*;
public class FlushablePoolTest {
@Test
public void initializeFlushablePoolTest1 () {
FlushablePoolClass flushablePool = new FlushablePoolClass();
assertEquals(0, flushablePool.getFree());
assertEquals(Integer.MAX_VALUE, flushablePool.max);
}
@Test
public void initializeFlushablePoolTest2 () {
FlushablePoolClass flushablePool = new FlushablePoolClass(10);
assertEquals(0, flushablePool.getFree());
assertEquals(Integer.MAX_VALUE, flushablePool.max);
}
@Test
public void initializeFlushablePoolTest3 () {
FlushablePoolClass flushablePool = new FlushablePoolClass(10, 10);
assertEquals(0, flushablePool.getFree());
assertEquals(10, flushablePool.max);
}
@Test
public void obtainTest () {
FlushablePoolClass flushablePool = new FlushablePoolClass(10, 10);
flushablePool.newObject();
assertEquals(0, flushablePool.obtained.size);
flushablePool.obtain();
assertEquals(1, flushablePool.obtained.size);
flushablePool.flush();
assertEquals(0, flushablePool.obtained.size);
}
@Test
public void flushTest () {
FlushablePoolClass flushablePool = new FlushablePoolClass(10, 10);
flushablePool.newObject();
flushablePool.obtain();
assertEquals(1, flushablePool.obtained.size);
flushablePool.flush();
assertEquals(0, flushablePool.obtained.size);
}
@Test
public void freeTest () {
// Create the flushable pool.
FlushablePoolClass flushablePool = new FlushablePoolClass(10, 10);
flushablePool.newObject();
flushablePool.newObject();
// Obtain the elements.
String element1 = flushablePool.obtain();
String element2 = flushablePool.obtain();
// Test preconditions.
assertTrue(flushablePool.obtained.contains(element1, true));
assertTrue(flushablePool.obtained.contains(element2, true));
// Free element and check containment.
flushablePool.free(element2);
assertTrue(flushablePool.obtained.contains(element1, true));
assertFalse(flushablePool.obtained.contains(element2, true));
}
@Test
public void freeAllTest () {
// Create the flushable pool.
FlushablePoolClass flushablePool = new FlushablePoolClass(5, 5);
flushablePool.newObject();
flushablePool.newObject();
// Obtain the elements.
final String element1 = flushablePool.obtain();
final String element2 = flushablePool.obtain();
// Create array with elements.
Array<String> elementArray = new Array<>();
elementArray.add(element1);
elementArray.add(element2);
// Test preconditions.
assertTrue(flushablePool.obtained.contains(element1, true));
assertTrue(flushablePool.obtained.contains(element2, true));
// Free elements and check containment.
flushablePool.freeAll(elementArray);
assertFalse(flushablePool.obtained.contains(element1, true));
assertFalse(flushablePool.obtained.contains(element2, true));
}
/** Test implementation class of FlushablePool. */
private class FlushablePoolClass extends FlushablePool<String> {
FlushablePoolClass () {
super();
}
FlushablePoolClass (int initialCapacity) {
super(initialCapacity);
}
FlushablePoolClass (int initialCapacity, int max) {
super(initialCapacity, max);
}
@Override
protected String newObject () {
return Integer.toString(getFree());
}
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./backends/gdx-backend-lwjgl3/src/com/badlogic/gdx/backends/lwjgl3/Lwjgl3ApplicationConfiguration.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl3;
import java.io.PrintStream;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.glfw.GLFWVidMode.Buffer;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.Graphics.Monitor;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Graphics.Lwjgl3Monitor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.HdpiMode;
import com.badlogic.gdx.graphics.glutils.HdpiUtils;
import com.badlogic.gdx.math.GridPoint2;
public class Lwjgl3ApplicationConfiguration extends Lwjgl3WindowConfiguration {
public static PrintStream errorStream = System.err;
boolean disableAudio = false;
/** The maximum number of threads to use for network requests. Default is {@link Integer#MAX_VALUE}. */
int maxNetThreads = Integer.MAX_VALUE;
int audioDeviceSimultaneousSources = 16;
int audioDeviceBufferSize = 512;
int audioDeviceBufferCount = 9;
public enum GLEmulation {
ANGLE_GLES20, GL20, GL30, GL31, GL32
}
GLEmulation glEmulation = GLEmulation.GL20;
int gles30ContextMajorVersion = 3;
int gles30ContextMinorVersion = 2;
int r = 8, g = 8, b = 8, a = 8;
int depth = 16, stencil = 0;
int samples = 0;
boolean transparentFramebuffer;
int idleFPS = 60;
int foregroundFPS = 0;
String preferencesDirectory = ".prefs/";
Files.FileType preferencesFileType = FileType.External;
HdpiMode hdpiMode = HdpiMode.Logical;
boolean debug = false;
PrintStream debugStream = System.err;
static Lwjgl3ApplicationConfiguration copy (Lwjgl3ApplicationConfiguration config) {
Lwjgl3ApplicationConfiguration copy = new Lwjgl3ApplicationConfiguration();
copy.set(config);
return copy;
}
void set (Lwjgl3ApplicationConfiguration config) {
super.setWindowConfiguration(config);
disableAudio = config.disableAudio;
audioDeviceSimultaneousSources = config.audioDeviceSimultaneousSources;
audioDeviceBufferSize = config.audioDeviceBufferSize;
audioDeviceBufferCount = config.audioDeviceBufferCount;
glEmulation = config.glEmulation;
gles30ContextMajorVersion = config.gles30ContextMajorVersion;
gles30ContextMinorVersion = config.gles30ContextMinorVersion;
r = config.r;
g = config.g;
b = config.b;
a = config.a;
depth = config.depth;
stencil = config.stencil;
samples = config.samples;
transparentFramebuffer = config.transparentFramebuffer;
idleFPS = config.idleFPS;
foregroundFPS = config.foregroundFPS;
preferencesDirectory = config.preferencesDirectory;
preferencesFileType = config.preferencesFileType;
hdpiMode = config.hdpiMode;
debug = config.debug;
debugStream = config.debugStream;
}
/** @param visibility whether the window will be visible on creation. (default true) */
public void setInitialVisible (boolean visibility) {
this.initialVisible = visibility;
}
/** Whether to disable audio or not. If set to true, the returned audio class instances like {@link Audio} or {@link Music}
* will be mock implementations. */
public void disableAudio (boolean disableAudio) {
this.disableAudio = disableAudio;
}
/** Sets the maximum number of threads to use for network requests. */
public void setMaxNetThreads (int maxNetThreads) {
this.maxNetThreads = maxNetThreads;
}
/** Sets the audio device configuration.
*
* @param simultaneousSources the maximum number of sources that can be played simultaniously (default 16)
* @param bufferSize the audio device buffer size in samples (default 512)
* @param bufferCount the audio device buffer count (default 9) */
public void setAudioConfig (int simultaneousSources, int bufferSize, int bufferCount) {
this.audioDeviceSimultaneousSources = simultaneousSources;
this.audioDeviceBufferSize = bufferSize;
this.audioDeviceBufferCount = bufferCount;
}
/** Sets which OpenGL version to use to emulate OpenGL ES. If the given major/minor version is not supported, the backend falls
* back to OpenGL ES 2.0 emulation through OpenGL 2.0. The default parameters for major and minor should be 3 and 2
* respectively to be compatible with Mac OS X. Specifying major version 4 and minor version 2 will ensure that all OpenGL ES
* 3.0 features are supported. Note however that Mac OS X does only support 3.2.
*
* @see <a href= "http://legacy.lwjgl.org/javadoc/org/lwjgl/opengl/ContextAttribs.html"> LWJGL OSX ContextAttribs note</a>
*
* @param glVersion which OpenGL ES emulation version to use
* @param gles3MajorVersion OpenGL ES major version, use 3 as default
* @param gles3MinorVersion OpenGL ES minor version, use 2 as default */
public void setOpenGLEmulation (GLEmulation glVersion, int gles3MajorVersion, int gles3MinorVersion) {
this.glEmulation = glVersion;
this.gles30ContextMajorVersion = gles3MajorVersion;
this.gles30ContextMinorVersion = gles3MinorVersion;
}
/** Sets the bit depth of the color, depth and stencil buffer as well as multi-sampling.
*
* @param r red bits (default 8)
* @param g green bits (default 8)
* @param b blue bits (default 8)
* @param a alpha bits (default 8)
* @param depth depth bits (default 16)
* @param stencil stencil bits (default 0)
* @param samples MSAA samples (default 0) */
public void setBackBufferConfig (int r, int g, int b, int a, int depth, int stencil, int samples) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
this.depth = depth;
this.stencil = stencil;
this.samples = samples;
}
/** Set transparent window hint. Results may vary on different OS and GPUs. Usage with the ANGLE backend is less consistent.
* @param transparentFramebuffer */
public void setTransparentFramebuffer (boolean transparentFramebuffer) {
this.transparentFramebuffer = transparentFramebuffer;
}
/** Sets the polling rate during idle time in non-continuous rendering mode. Must be positive. Default is 60. */
public void setIdleFPS (int fps) {
this.idleFPS = fps;
}
/** Sets the target framerate for the application. The CPU sleeps as needed. Must be positive. Use 0 to never sleep. Default is
* 0. */
public void setForegroundFPS (int fps) {
this.foregroundFPS = fps;
}
/** Sets the directory where {@link Preferences} will be stored, as well as the file type to be used to store them. Defaults to
* "$USER_HOME/.prefs/" and {@link FileType#External}. */
public void setPreferencesConfig (String preferencesDirectory, Files.FileType preferencesFileType) {
this.preferencesDirectory = preferencesDirectory;
this.preferencesFileType = preferencesFileType;
}
/** Defines how HDPI monitors are handled. Operating systems may have a per-monitor HDPI scale setting. The operating system
* may report window width/height and mouse coordinates in a logical coordinate system at a lower resolution than the actual
* physical resolution. This setting allows you to specify whether you want to work in logical or raw pixel units. See
* {@link HdpiMode} for more information. Note that some OpenGL functions like {@link GL20#glViewport(int, int, int, int)} and
* {@link GL20#glScissor(int, int, int, int)} require raw pixel units. Use {@link HdpiUtils} to help with the conversion if
* HdpiMode is set to {@link HdpiMode#Logical}. Defaults to {@link HdpiMode#Logical}. */
public void setHdpiMode (HdpiMode mode) {
this.hdpiMode = mode;
}
/** Enables use of OpenGL debug message callbacks. If not supported by the core GL driver (since GL 4.3), this uses the
* KHR_debug, ARB_debug_output or AMD_debug_output extension if available. By default, debug messages with NOTIFICATION
* severity are disabled to avoid log spam.
*
* You can call with {@link System#err} to output to the "standard" error output stream.
*
* Use {@link Lwjgl3Application#setGLDebugMessageControl(Lwjgl3Application.GLDebugMessageSeverity, boolean)} to enable or
* disable other severity debug levels. */
public void enableGLDebugOutput (boolean enable, PrintStream debugOutputStream) {
debug = enable;
debugStream = debugOutputStream;
}
/** @return the currently active {@link DisplayMode} of the primary monitor */
public static DisplayMode getDisplayMode () {
Lwjgl3Application.initializeGlfw();
GLFWVidMode videoMode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());
return new Lwjgl3Graphics.Lwjgl3DisplayMode(GLFW.glfwGetPrimaryMonitor(), videoMode.width(), videoMode.height(),
videoMode.refreshRate(), videoMode.redBits() + videoMode.greenBits() + videoMode.blueBits());
}
/** @return the currently active {@link DisplayMode} of the given monitor */
public static DisplayMode getDisplayMode (Monitor monitor) {
Lwjgl3Application.initializeGlfw();
GLFWVidMode videoMode = GLFW.glfwGetVideoMode(((Lwjgl3Monitor)monitor).monitorHandle);
return new Lwjgl3Graphics.Lwjgl3DisplayMode(((Lwjgl3Monitor)monitor).monitorHandle, videoMode.width(), videoMode.height(),
videoMode.refreshRate(), videoMode.redBits() + videoMode.greenBits() + videoMode.blueBits());
}
/** @return the available {@link DisplayMode}s of the primary monitor */
public static DisplayMode[] getDisplayModes () {
Lwjgl3Application.initializeGlfw();
Buffer videoModes = GLFW.glfwGetVideoModes(GLFW.glfwGetPrimaryMonitor());
DisplayMode[] result = new DisplayMode[videoModes.limit()];
for (int i = 0; i < result.length; i++) {
GLFWVidMode videoMode = videoModes.get(i);
result[i] = new Lwjgl3Graphics.Lwjgl3DisplayMode(GLFW.glfwGetPrimaryMonitor(), videoMode.width(), videoMode.height(),
videoMode.refreshRate(), videoMode.redBits() + videoMode.greenBits() + videoMode.blueBits());
}
return result;
}
/** @return the available {@link DisplayMode}s of the given {@link Monitor} */
public static DisplayMode[] getDisplayModes (Monitor monitor) {
Lwjgl3Application.initializeGlfw();
Buffer videoModes = GLFW.glfwGetVideoModes(((Lwjgl3Monitor)monitor).monitorHandle);
DisplayMode[] result = new DisplayMode[videoModes.limit()];
for (int i = 0; i < result.length; i++) {
GLFWVidMode videoMode = videoModes.get(i);
result[i] = new Lwjgl3Graphics.Lwjgl3DisplayMode(((Lwjgl3Monitor)monitor).monitorHandle, videoMode.width(),
videoMode.height(), videoMode.refreshRate(), videoMode.redBits() + videoMode.greenBits() + videoMode.blueBits());
}
return result;
}
/** @return the primary {@link Monitor} */
public static Monitor getPrimaryMonitor () {
Lwjgl3Application.initializeGlfw();
return toLwjgl3Monitor(GLFW.glfwGetPrimaryMonitor());
}
/** @return the connected {@link Monitor}s */
public static Monitor[] getMonitors () {
Lwjgl3Application.initializeGlfw();
PointerBuffer glfwMonitors = GLFW.glfwGetMonitors();
Monitor[] monitors = new Monitor[glfwMonitors.limit()];
for (int i = 0; i < glfwMonitors.limit(); i++) {
monitors[i] = toLwjgl3Monitor(glfwMonitors.get(i));
}
return monitors;
}
static Lwjgl3Monitor toLwjgl3Monitor (long glfwMonitor) {
IntBuffer tmp = BufferUtils.createIntBuffer(1);
IntBuffer tmp2 = BufferUtils.createIntBuffer(1);
GLFW.glfwGetMonitorPos(glfwMonitor, tmp, tmp2);
int virtualX = tmp.get(0);
int virtualY = tmp2.get(0);
String name = GLFW.glfwGetMonitorName(glfwMonitor);
return new Lwjgl3Monitor(glfwMonitor, virtualX, virtualY, name);
}
static GridPoint2 calculateCenteredWindowPosition (Lwjgl3Monitor monitor, int newWidth, int newHeight) {
IntBuffer tmp = BufferUtils.createIntBuffer(1);
IntBuffer tmp2 = BufferUtils.createIntBuffer(1);
IntBuffer tmp3 = BufferUtils.createIntBuffer(1);
IntBuffer tmp4 = BufferUtils.createIntBuffer(1);
DisplayMode displayMode = getDisplayMode(monitor);
GLFW.glfwGetMonitorWorkarea(monitor.monitorHandle, tmp, tmp2, tmp3, tmp4);
int workareaWidth = tmp3.get(0);
int workareaHeight = tmp4.get(0);
int minX, minY, maxX, maxY;
// If the new width is greater than the working area, we have to ignore stuff like the taskbar for centering and use the
// whole monitor's size
if (newWidth > workareaWidth) {
minX = monitor.virtualX;
maxX = displayMode.width;
} else {
minX = tmp.get(0);
maxX = workareaWidth;
}
// The same is true for height
if (newHeight > workareaHeight) {
minY = monitor.virtualY;
maxY = displayMode.height;
} else {
minY = tmp2.get(0);
maxY = workareaHeight;
}
return new GridPoint2(Math.max(minX, minX + (maxX - newWidth) / 2), Math.max(minY, minY + (maxY - newHeight) / 2));
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl3;
import java.io.PrintStream;
import java.nio.IntBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.glfw.GLFWVidMode.Buffer;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Files.FileType;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.Graphics.Monitor;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Graphics.Lwjgl3Monitor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.HdpiMode;
import com.badlogic.gdx.graphics.glutils.HdpiUtils;
import com.badlogic.gdx.math.GridPoint2;
public class Lwjgl3ApplicationConfiguration extends Lwjgl3WindowConfiguration {
public static PrintStream errorStream = System.err;
boolean disableAudio = false;
/** The maximum number of threads to use for network requests. Default is {@link Integer#MAX_VALUE}. */
int maxNetThreads = Integer.MAX_VALUE;
int audioDeviceSimultaneousSources = 16;
int audioDeviceBufferSize = 512;
int audioDeviceBufferCount = 9;
public enum GLEmulation {
ANGLE_GLES20, GL20, GL30, GL31, GL32
}
GLEmulation glEmulation = GLEmulation.GL20;
int gles30ContextMajorVersion = 3;
int gles30ContextMinorVersion = 2;
int r = 8, g = 8, b = 8, a = 8;
int depth = 16, stencil = 0;
int samples = 0;
boolean transparentFramebuffer;
int idleFPS = 60;
int foregroundFPS = 0;
String preferencesDirectory = ".prefs/";
Files.FileType preferencesFileType = FileType.External;
HdpiMode hdpiMode = HdpiMode.Logical;
boolean debug = false;
PrintStream debugStream = System.err;
static Lwjgl3ApplicationConfiguration copy (Lwjgl3ApplicationConfiguration config) {
Lwjgl3ApplicationConfiguration copy = new Lwjgl3ApplicationConfiguration();
copy.set(config);
return copy;
}
void set (Lwjgl3ApplicationConfiguration config) {
super.setWindowConfiguration(config);
disableAudio = config.disableAudio;
audioDeviceSimultaneousSources = config.audioDeviceSimultaneousSources;
audioDeviceBufferSize = config.audioDeviceBufferSize;
audioDeviceBufferCount = config.audioDeviceBufferCount;
glEmulation = config.glEmulation;
gles30ContextMajorVersion = config.gles30ContextMajorVersion;
gles30ContextMinorVersion = config.gles30ContextMinorVersion;
r = config.r;
g = config.g;
b = config.b;
a = config.a;
depth = config.depth;
stencil = config.stencil;
samples = config.samples;
transparentFramebuffer = config.transparentFramebuffer;
idleFPS = config.idleFPS;
foregroundFPS = config.foregroundFPS;
preferencesDirectory = config.preferencesDirectory;
preferencesFileType = config.preferencesFileType;
hdpiMode = config.hdpiMode;
debug = config.debug;
debugStream = config.debugStream;
}
/** @param visibility whether the window will be visible on creation. (default true) */
public void setInitialVisible (boolean visibility) {
this.initialVisible = visibility;
}
/** Whether to disable audio or not. If set to true, the returned audio class instances like {@link Audio} or {@link Music}
* will be mock implementations. */
public void disableAudio (boolean disableAudio) {
this.disableAudio = disableAudio;
}
/** Sets the maximum number of threads to use for network requests. */
public void setMaxNetThreads (int maxNetThreads) {
this.maxNetThreads = maxNetThreads;
}
/** Sets the audio device configuration.
*
* @param simultaneousSources the maximum number of sources that can be played simultaniously (default 16)
* @param bufferSize the audio device buffer size in samples (default 512)
* @param bufferCount the audio device buffer count (default 9) */
public void setAudioConfig (int simultaneousSources, int bufferSize, int bufferCount) {
this.audioDeviceSimultaneousSources = simultaneousSources;
this.audioDeviceBufferSize = bufferSize;
this.audioDeviceBufferCount = bufferCount;
}
/** Sets which OpenGL version to use to emulate OpenGL ES. If the given major/minor version is not supported, the backend falls
* back to OpenGL ES 2.0 emulation through OpenGL 2.0. The default parameters for major and minor should be 3 and 2
* respectively to be compatible with Mac OS X. Specifying major version 4 and minor version 2 will ensure that all OpenGL ES
* 3.0 features are supported. Note however that Mac OS X does only support 3.2.
*
* @see <a href= "http://legacy.lwjgl.org/javadoc/org/lwjgl/opengl/ContextAttribs.html"> LWJGL OSX ContextAttribs note</a>
*
* @param glVersion which OpenGL ES emulation version to use
* @param gles3MajorVersion OpenGL ES major version, use 3 as default
* @param gles3MinorVersion OpenGL ES minor version, use 2 as default */
public void setOpenGLEmulation (GLEmulation glVersion, int gles3MajorVersion, int gles3MinorVersion) {
this.glEmulation = glVersion;
this.gles30ContextMajorVersion = gles3MajorVersion;
this.gles30ContextMinorVersion = gles3MinorVersion;
}
/** Sets the bit depth of the color, depth and stencil buffer as well as multi-sampling.
*
* @param r red bits (default 8)
* @param g green bits (default 8)
* @param b blue bits (default 8)
* @param a alpha bits (default 8)
* @param depth depth bits (default 16)
* @param stencil stencil bits (default 0)
* @param samples MSAA samples (default 0) */
public void setBackBufferConfig (int r, int g, int b, int a, int depth, int stencil, int samples) {
this.r = r;
this.g = g;
this.b = b;
this.a = a;
this.depth = depth;
this.stencil = stencil;
this.samples = samples;
}
/** Set transparent window hint. Results may vary on different OS and GPUs. Usage with the ANGLE backend is less consistent.
* @param transparentFramebuffer */
public void setTransparentFramebuffer (boolean transparentFramebuffer) {
this.transparentFramebuffer = transparentFramebuffer;
}
/** Sets the polling rate during idle time in non-continuous rendering mode. Must be positive. Default is 60. */
public void setIdleFPS (int fps) {
this.idleFPS = fps;
}
/** Sets the target framerate for the application. The CPU sleeps as needed. Must be positive. Use 0 to never sleep. Default is
* 0. */
public void setForegroundFPS (int fps) {
this.foregroundFPS = fps;
}
/** Sets the directory where {@link Preferences} will be stored, as well as the file type to be used to store them. Defaults to
* "$USER_HOME/.prefs/" and {@link FileType#External}. */
public void setPreferencesConfig (String preferencesDirectory, Files.FileType preferencesFileType) {
this.preferencesDirectory = preferencesDirectory;
this.preferencesFileType = preferencesFileType;
}
/** Defines how HDPI monitors are handled. Operating systems may have a per-monitor HDPI scale setting. The operating system
* may report window width/height and mouse coordinates in a logical coordinate system at a lower resolution than the actual
* physical resolution. This setting allows you to specify whether you want to work in logical or raw pixel units. See
* {@link HdpiMode} for more information. Note that some OpenGL functions like {@link GL20#glViewport(int, int, int, int)} and
* {@link GL20#glScissor(int, int, int, int)} require raw pixel units. Use {@link HdpiUtils} to help with the conversion if
* HdpiMode is set to {@link HdpiMode#Logical}. Defaults to {@link HdpiMode#Logical}. */
public void setHdpiMode (HdpiMode mode) {
this.hdpiMode = mode;
}
/** Enables use of OpenGL debug message callbacks. If not supported by the core GL driver (since GL 4.3), this uses the
* KHR_debug, ARB_debug_output or AMD_debug_output extension if available. By default, debug messages with NOTIFICATION
* severity are disabled to avoid log spam.
*
* You can call with {@link System#err} to output to the "standard" error output stream.
*
* Use {@link Lwjgl3Application#setGLDebugMessageControl(Lwjgl3Application.GLDebugMessageSeverity, boolean)} to enable or
* disable other severity debug levels. */
public void enableGLDebugOutput (boolean enable, PrintStream debugOutputStream) {
debug = enable;
debugStream = debugOutputStream;
}
/** @return the currently active {@link DisplayMode} of the primary monitor */
public static DisplayMode getDisplayMode () {
Lwjgl3Application.initializeGlfw();
GLFWVidMode videoMode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());
return new Lwjgl3Graphics.Lwjgl3DisplayMode(GLFW.glfwGetPrimaryMonitor(), videoMode.width(), videoMode.height(),
videoMode.refreshRate(), videoMode.redBits() + videoMode.greenBits() + videoMode.blueBits());
}
/** @return the currently active {@link DisplayMode} of the given monitor */
public static DisplayMode getDisplayMode (Monitor monitor) {
Lwjgl3Application.initializeGlfw();
GLFWVidMode videoMode = GLFW.glfwGetVideoMode(((Lwjgl3Monitor)monitor).monitorHandle);
return new Lwjgl3Graphics.Lwjgl3DisplayMode(((Lwjgl3Monitor)monitor).monitorHandle, videoMode.width(), videoMode.height(),
videoMode.refreshRate(), videoMode.redBits() + videoMode.greenBits() + videoMode.blueBits());
}
/** @return the available {@link DisplayMode}s of the primary monitor */
public static DisplayMode[] getDisplayModes () {
Lwjgl3Application.initializeGlfw();
Buffer videoModes = GLFW.glfwGetVideoModes(GLFW.glfwGetPrimaryMonitor());
DisplayMode[] result = new DisplayMode[videoModes.limit()];
for (int i = 0; i < result.length; i++) {
GLFWVidMode videoMode = videoModes.get(i);
result[i] = new Lwjgl3Graphics.Lwjgl3DisplayMode(GLFW.glfwGetPrimaryMonitor(), videoMode.width(), videoMode.height(),
videoMode.refreshRate(), videoMode.redBits() + videoMode.greenBits() + videoMode.blueBits());
}
return result;
}
/** @return the available {@link DisplayMode}s of the given {@link Monitor} */
public static DisplayMode[] getDisplayModes (Monitor monitor) {
Lwjgl3Application.initializeGlfw();
Buffer videoModes = GLFW.glfwGetVideoModes(((Lwjgl3Monitor)monitor).monitorHandle);
DisplayMode[] result = new DisplayMode[videoModes.limit()];
for (int i = 0; i < result.length; i++) {
GLFWVidMode videoMode = videoModes.get(i);
result[i] = new Lwjgl3Graphics.Lwjgl3DisplayMode(((Lwjgl3Monitor)monitor).monitorHandle, videoMode.width(),
videoMode.height(), videoMode.refreshRate(), videoMode.redBits() + videoMode.greenBits() + videoMode.blueBits());
}
return result;
}
/** @return the primary {@link Monitor} */
public static Monitor getPrimaryMonitor () {
Lwjgl3Application.initializeGlfw();
return toLwjgl3Monitor(GLFW.glfwGetPrimaryMonitor());
}
/** @return the connected {@link Monitor}s */
public static Monitor[] getMonitors () {
Lwjgl3Application.initializeGlfw();
PointerBuffer glfwMonitors = GLFW.glfwGetMonitors();
Monitor[] monitors = new Monitor[glfwMonitors.limit()];
for (int i = 0; i < glfwMonitors.limit(); i++) {
monitors[i] = toLwjgl3Monitor(glfwMonitors.get(i));
}
return monitors;
}
static Lwjgl3Monitor toLwjgl3Monitor (long glfwMonitor) {
IntBuffer tmp = BufferUtils.createIntBuffer(1);
IntBuffer tmp2 = BufferUtils.createIntBuffer(1);
GLFW.glfwGetMonitorPos(glfwMonitor, tmp, tmp2);
int virtualX = tmp.get(0);
int virtualY = tmp2.get(0);
String name = GLFW.glfwGetMonitorName(glfwMonitor);
return new Lwjgl3Monitor(glfwMonitor, virtualX, virtualY, name);
}
static GridPoint2 calculateCenteredWindowPosition (Lwjgl3Monitor monitor, int newWidth, int newHeight) {
IntBuffer tmp = BufferUtils.createIntBuffer(1);
IntBuffer tmp2 = BufferUtils.createIntBuffer(1);
IntBuffer tmp3 = BufferUtils.createIntBuffer(1);
IntBuffer tmp4 = BufferUtils.createIntBuffer(1);
DisplayMode displayMode = getDisplayMode(monitor);
GLFW.glfwGetMonitorWorkarea(monitor.monitorHandle, tmp, tmp2, tmp3, tmp4);
int workareaWidth = tmp3.get(0);
int workareaHeight = tmp4.get(0);
int minX, minY, maxX, maxY;
// If the new width is greater than the working area, we have to ignore stuff like the taskbar for centering and use the
// whole monitor's size
if (newWidth > workareaWidth) {
minX = monitor.virtualX;
maxX = displayMode.width;
} else {
minX = tmp.get(0);
maxX = workareaWidth;
}
// The same is true for height
if (newHeight > workareaHeight) {
minY = monitor.virtualY;
maxY = displayMode.height;
} else {
minY = tmp2.get(0);
maxY = workareaHeight;
}
return new GridPoint2(Math.max(minX, minX + (maxX - newWidth) / 2), Math.max(minY, minY + (maxY - newHeight) / 2));
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/dynamics/joints/WheelJoint.java | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.dynamics.joints;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Rot;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.SolverData;
import org.jbox2d.pooling.IWorldPool;
//Linear constraint (point-to-line)
//d = pB - pA = xB + rB - xA - rA
//C = dot(ay, d)
//Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA))
// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB)
//J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)]
//Spring linear constraint
//C = dot(ax, d)
//Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB)
//J = [-ax -cross(d+rA, ax) ax cross(rB, ax)]
//Motor rotational constraint
//Cdot = wB - wA
//J = [0 0 -1 0 0 1]
/** A wheel joint. This joint provides two degrees of freedom: translation along an axis fixed in bodyA and rotation in the plane.
* You can use a joint limit to restrict the range of motion and a joint motor to drive the rotation or to model rotational
* friction. This joint is designed for vehicle suspensions.
*
* @author Daniel Murphy */
public class WheelJoint extends Joint {
private float m_frequencyHz;
private float m_dampingRatio;
// Solver shared
private final Vec2 m_localAnchorA = new Vec2();
private final Vec2 m_localAnchorB = new Vec2();
private final Vec2 m_localXAxisA = new Vec2();
private final Vec2 m_localYAxisA = new Vec2();
private float m_impulse;
private float m_motorImpulse;
private float m_springImpulse;
private float m_maxMotorTorque;
private float m_motorSpeed;
private boolean m_enableMotor;
// Solver temp
private int m_indexA;
private int m_indexB;
private final Vec2 m_localCenterA = new Vec2();
private final Vec2 m_localCenterB = new Vec2();
private float m_invMassA;
private float m_invMassB;
private float m_invIA;
private float m_invIB;
private final Vec2 m_ax = new Vec2();
private final Vec2 m_ay = new Vec2();
private float m_sAx, m_sBx;
private float m_sAy, m_sBy;
private float m_mass;
private float m_motorMass;
private float m_springMass;
private float m_bias;
private float m_gamma;
protected WheelJoint (IWorldPool argPool, WheelJointDef def) {
super(argPool, def);
m_localAnchorA.set(def.localAnchorA);
m_localAnchorB.set(def.localAnchorB);
m_localXAxisA.set(def.localAxisA);
Vec2.crossToOutUnsafe(1.0f, m_localXAxisA, m_localYAxisA);
m_motorMass = 0.0f;
m_motorImpulse = 0.0f;
m_maxMotorTorque = def.maxMotorTorque;
m_motorSpeed = def.motorSpeed;
m_enableMotor = def.enableMotor;
m_frequencyHz = def.frequencyHz;
m_dampingRatio = def.dampingRatio;
}
public Vec2 getLocalAnchorA () {
return m_localAnchorA;
}
public Vec2 getLocalAnchorB () {
return m_localAnchorB;
}
@Override
public void getAnchorA (Vec2 argOut) {
m_bodyA.getWorldPointToOut(m_localAnchorA, argOut);
}
@Override
public void getAnchorB (Vec2 argOut) {
m_bodyB.getWorldPointToOut(m_localAnchorB, argOut);
}
@Override
public void getReactionForce (float inv_dt, Vec2 argOut) {
final Vec2 temp = pool.popVec2();
temp.set(m_ay).mulLocal(m_impulse);
argOut.set(m_ax).mulLocal(m_springImpulse).addLocal(temp).mulLocal(inv_dt);
pool.pushVec2(1);
}
@Override
public float getReactionTorque (float inv_dt) {
return inv_dt * m_motorImpulse;
}
public float getJointTranslation () {
Body b1 = m_bodyA;
Body b2 = m_bodyB;
Vec2 p1 = pool.popVec2();
Vec2 p2 = pool.popVec2();
Vec2 axis = pool.popVec2();
b1.getWorldPointToOut(m_localAnchorA, p1);
b2.getWorldPointToOut(m_localAnchorA, p2);
p2.subLocal(p1);
b1.getWorldVectorToOut(m_localXAxisA, axis);
float translation = Vec2.dot(p2, axis);
pool.pushVec2(3);
return translation;
}
/** For serialization */
public Vec2 getLocalAxisA () {
return m_localXAxisA;
}
public float getJointSpeed () {
return m_bodyA.m_angularVelocity - m_bodyB.m_angularVelocity;
}
public boolean isMotorEnabled () {
return m_enableMotor;
}
public void enableMotor (boolean flag) {
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_enableMotor = flag;
}
public void setMotorSpeed (float speed) {
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_motorSpeed = speed;
}
public float getMotorSpeed () {
return m_motorSpeed;
}
public float getMaxMotorTorque () {
return m_maxMotorTorque;
}
public void setMaxMotorTorque (float torque) {
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_maxMotorTorque = torque;
}
public float getMotorTorque (float inv_dt) {
return m_motorImpulse * inv_dt;
}
public void setSpringFrequencyHz (float hz) {
m_frequencyHz = hz;
}
public float getSpringFrequencyHz () {
return m_frequencyHz;
}
public void setSpringDampingRatio (float ratio) {
m_dampingRatio = ratio;
}
public float getSpringDampingRatio () {
return m_dampingRatio;
}
// pooling
private final Vec2 rA = new Vec2();
private final Vec2 rB = new Vec2();
private final Vec2 d = new Vec2();
@Override
public void initVelocityConstraints (SolverData data) {
m_indexA = m_bodyA.m_islandIndex;
m_indexB = m_bodyB.m_islandIndex;
m_localCenterA.set(m_bodyA.m_sweep.localCenter);
m_localCenterB.set(m_bodyB.m_sweep.localCenter);
m_invMassA = m_bodyA.m_invMass;
m_invMassB = m_bodyB.m_invMass;
m_invIA = m_bodyA.m_invI;
m_invIB = m_bodyB.m_invI;
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
final Rot qA = pool.popRot();
final Rot qB = pool.popRot();
final Vec2 temp = pool.popVec2();
qA.set(aA);
qB.set(aB);
// Compute the effective masses.
Rot.mulToOutUnsafe(qA, temp.set(m_localAnchorA).subLocal(m_localCenterA), rA);
Rot.mulToOutUnsafe(qB, temp.set(m_localAnchorB).subLocal(m_localCenterB), rB);
d.set(cB).addLocal(rB).subLocal(cA).subLocal(rA);
// Point to line constraint
{
Rot.mulToOut(qA, m_localYAxisA, m_ay);
m_sAy = Vec2.cross(temp.set(d).addLocal(rA), m_ay);
m_sBy = Vec2.cross(rB, m_ay);
m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy;
if (m_mass > 0.0f) {
m_mass = 1.0f / m_mass;
}
}
// Spring constraint
m_springMass = 0.0f;
m_bias = 0.0f;
m_gamma = 0.0f;
if (m_frequencyHz > 0.0f) {
Rot.mulToOut(qA, m_localXAxisA, m_ax);
m_sAx = Vec2.cross(temp.set(d).addLocal(rA), m_ax);
m_sBx = Vec2.cross(rB, m_ax);
float invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx;
if (invMass > 0.0f) {
m_springMass = 1.0f / invMass;
float C = Vec2.dot(d, m_ax);
// Frequency
float omega = 2.0f * MathUtils.PI * m_frequencyHz;
// Damping coefficient
float d = 2.0f * m_springMass * m_dampingRatio * omega;
// Spring stiffness
float k = m_springMass * omega * omega;
// magic formulas
float h = data.step.dt;
m_gamma = h * (d + h * k);
if (m_gamma > 0.0f) {
m_gamma = 1.0f / m_gamma;
}
m_bias = C * h * k * m_gamma;
m_springMass = invMass + m_gamma;
if (m_springMass > 0.0f) {
m_springMass = 1.0f / m_springMass;
}
}
} else {
m_springImpulse = 0.0f;
}
// Rotational motor
if (m_enableMotor) {
m_motorMass = iA + iB;
if (m_motorMass > 0.0f) {
m_motorMass = 1.0f / m_motorMass;
}
} else {
m_motorMass = 0.0f;
m_motorImpulse = 0.0f;
}
if (data.step.warmStarting) {
final Vec2 P = pool.popVec2();
// Account for variable time step.
m_impulse *= data.step.dtRatio;
m_springImpulse *= data.step.dtRatio;
m_motorImpulse *= data.step.dtRatio;
P.x = m_impulse * m_ay.x + m_springImpulse * m_ax.x;
P.y = m_impulse * m_ay.y + m_springImpulse * m_ax.y;
float LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse;
float LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse;
vA.x -= m_invMassA * P.x;
vA.y -= m_invMassA * P.y;
wA -= m_invIA * LA;
vB.x += m_invMassB * P.x;
vB.y += m_invMassB * P.y;
wB += m_invIB * LB;
pool.pushVec2(1);
} else {
m_impulse = 0.0f;
m_springImpulse = 0.0f;
m_motorImpulse = 0.0f;
}
pool.pushRot(2);
pool.pushVec2(1);
// data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
@Override
public void solveVelocityConstraints (SolverData data) {
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
final Vec2 temp = pool.popVec2();
final Vec2 P = pool.popVec2();
// Solve spring constraint
{
float Cdot = Vec2.dot(m_ax, temp.set(vB).subLocal(vA)) + m_sBx * wB - m_sAx * wA;
float impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse);
m_springImpulse += impulse;
P.x = impulse * m_ax.x;
P.y = impulse * m_ax.y;
float LA = impulse * m_sAx;
float LB = impulse * m_sBx;
vA.x -= mA * P.x;
vA.y -= mA * P.y;
wA -= iA * LA;
vB.x += mB * P.x;
vB.y += mB * P.y;
wB += iB * LB;
}
// Solve rotational motor constraint
{
float Cdot = wB - wA - m_motorSpeed;
float impulse = -m_motorMass * Cdot;
float oldImpulse = m_motorImpulse;
float maxImpulse = data.step.dt * m_maxMotorTorque;
m_motorImpulse = MathUtils.clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve point to line constraint
{
float Cdot = Vec2.dot(m_ay, temp.set(vB).subLocal(vA)) + m_sBy * wB - m_sAy * wA;
float impulse = -m_mass * Cdot;
m_impulse += impulse;
P.x = impulse * m_ay.x;
P.y = impulse * m_ay.y;
float LA = impulse * m_sAy;
float LB = impulse * m_sBy;
vA.x -= mA * P.x;
vA.y -= mA * P.y;
wA -= iA * LA;
vB.x += mB * P.x;
vB.y += mB * P.y;
wB += iB * LB;
}
pool.pushVec2(2);
// data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
@Override
public boolean solvePositionConstraints (SolverData data) {
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
final Rot qA = pool.popRot();
final Rot qB = pool.popRot();
final Vec2 temp = pool.popVec2();
qA.set(aA);
qB.set(aB);
Rot.mulToOut(qA, temp.set(m_localAnchorA).subLocal(m_localCenterA), rA);
Rot.mulToOut(qB, temp.set(m_localAnchorB).subLocal(m_localCenterB), rB);
d.set(cB).subLocal(cA).addLocal(rB).subLocal(rA);
Vec2 ay = pool.popVec2();
Rot.mulToOut(qA, m_localYAxisA, ay);
float sAy = Vec2.cross(temp.set(d).addLocal(rA), ay);
float sBy = Vec2.cross(rB, ay);
float C = Vec2.dot(d, ay);
float k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy;
float impulse;
if (k != 0.0f) {
impulse = -C / k;
} else {
impulse = 0.0f;
}
final Vec2 P = pool.popVec2();
P.x = impulse * ay.x;
P.y = impulse * ay.y;
float LA = impulse * sAy;
float LB = impulse * sBy;
cA.x -= m_invMassA * P.x;
cA.y -= m_invMassA * P.y;
aA -= m_invIA * LA;
cB.x += m_invMassB * P.x;
cB.y += m_invMassB * P.y;
aB += m_invIB * LB;
pool.pushVec2(3);
pool.pushRot(2);
// data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
// data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
return MathUtils.abs(C) <= Settings.linearSlop;
}
}
| /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.dynamics.joints;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Rot;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.SolverData;
import org.jbox2d.pooling.IWorldPool;
//Linear constraint (point-to-line)
//d = pB - pA = xB + rB - xA - rA
//C = dot(ay, d)
//Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA))
// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB)
//J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)]
//Spring linear constraint
//C = dot(ax, d)
//Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB)
//J = [-ax -cross(d+rA, ax) ax cross(rB, ax)]
//Motor rotational constraint
//Cdot = wB - wA
//J = [0 0 -1 0 0 1]
/** A wheel joint. This joint provides two degrees of freedom: translation along an axis fixed in bodyA and rotation in the plane.
* You can use a joint limit to restrict the range of motion and a joint motor to drive the rotation or to model rotational
* friction. This joint is designed for vehicle suspensions.
*
* @author Daniel Murphy */
public class WheelJoint extends Joint {
private float m_frequencyHz;
private float m_dampingRatio;
// Solver shared
private final Vec2 m_localAnchorA = new Vec2();
private final Vec2 m_localAnchorB = new Vec2();
private final Vec2 m_localXAxisA = new Vec2();
private final Vec2 m_localYAxisA = new Vec2();
private float m_impulse;
private float m_motorImpulse;
private float m_springImpulse;
private float m_maxMotorTorque;
private float m_motorSpeed;
private boolean m_enableMotor;
// Solver temp
private int m_indexA;
private int m_indexB;
private final Vec2 m_localCenterA = new Vec2();
private final Vec2 m_localCenterB = new Vec2();
private float m_invMassA;
private float m_invMassB;
private float m_invIA;
private float m_invIB;
private final Vec2 m_ax = new Vec2();
private final Vec2 m_ay = new Vec2();
private float m_sAx, m_sBx;
private float m_sAy, m_sBy;
private float m_mass;
private float m_motorMass;
private float m_springMass;
private float m_bias;
private float m_gamma;
protected WheelJoint (IWorldPool argPool, WheelJointDef def) {
super(argPool, def);
m_localAnchorA.set(def.localAnchorA);
m_localAnchorB.set(def.localAnchorB);
m_localXAxisA.set(def.localAxisA);
Vec2.crossToOutUnsafe(1.0f, m_localXAxisA, m_localYAxisA);
m_motorMass = 0.0f;
m_motorImpulse = 0.0f;
m_maxMotorTorque = def.maxMotorTorque;
m_motorSpeed = def.motorSpeed;
m_enableMotor = def.enableMotor;
m_frequencyHz = def.frequencyHz;
m_dampingRatio = def.dampingRatio;
}
public Vec2 getLocalAnchorA () {
return m_localAnchorA;
}
public Vec2 getLocalAnchorB () {
return m_localAnchorB;
}
@Override
public void getAnchorA (Vec2 argOut) {
m_bodyA.getWorldPointToOut(m_localAnchorA, argOut);
}
@Override
public void getAnchorB (Vec2 argOut) {
m_bodyB.getWorldPointToOut(m_localAnchorB, argOut);
}
@Override
public void getReactionForce (float inv_dt, Vec2 argOut) {
final Vec2 temp = pool.popVec2();
temp.set(m_ay).mulLocal(m_impulse);
argOut.set(m_ax).mulLocal(m_springImpulse).addLocal(temp).mulLocal(inv_dt);
pool.pushVec2(1);
}
@Override
public float getReactionTorque (float inv_dt) {
return inv_dt * m_motorImpulse;
}
public float getJointTranslation () {
Body b1 = m_bodyA;
Body b2 = m_bodyB;
Vec2 p1 = pool.popVec2();
Vec2 p2 = pool.popVec2();
Vec2 axis = pool.popVec2();
b1.getWorldPointToOut(m_localAnchorA, p1);
b2.getWorldPointToOut(m_localAnchorA, p2);
p2.subLocal(p1);
b1.getWorldVectorToOut(m_localXAxisA, axis);
float translation = Vec2.dot(p2, axis);
pool.pushVec2(3);
return translation;
}
/** For serialization */
public Vec2 getLocalAxisA () {
return m_localXAxisA;
}
public float getJointSpeed () {
return m_bodyA.m_angularVelocity - m_bodyB.m_angularVelocity;
}
public boolean isMotorEnabled () {
return m_enableMotor;
}
public void enableMotor (boolean flag) {
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_enableMotor = flag;
}
public void setMotorSpeed (float speed) {
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_motorSpeed = speed;
}
public float getMotorSpeed () {
return m_motorSpeed;
}
public float getMaxMotorTorque () {
return m_maxMotorTorque;
}
public void setMaxMotorTorque (float torque) {
m_bodyA.setAwake(true);
m_bodyB.setAwake(true);
m_maxMotorTorque = torque;
}
public float getMotorTorque (float inv_dt) {
return m_motorImpulse * inv_dt;
}
public void setSpringFrequencyHz (float hz) {
m_frequencyHz = hz;
}
public float getSpringFrequencyHz () {
return m_frequencyHz;
}
public void setSpringDampingRatio (float ratio) {
m_dampingRatio = ratio;
}
public float getSpringDampingRatio () {
return m_dampingRatio;
}
// pooling
private final Vec2 rA = new Vec2();
private final Vec2 rB = new Vec2();
private final Vec2 d = new Vec2();
@Override
public void initVelocityConstraints (SolverData data) {
m_indexA = m_bodyA.m_islandIndex;
m_indexB = m_bodyB.m_islandIndex;
m_localCenterA.set(m_bodyA.m_sweep.localCenter);
m_localCenterB.set(m_bodyB.m_sweep.localCenter);
m_invMassA = m_bodyA.m_invMass;
m_invMassB = m_bodyB.m_invMass;
m_invIA = m_bodyA.m_invI;
m_invIB = m_bodyB.m_invI;
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
final Rot qA = pool.popRot();
final Rot qB = pool.popRot();
final Vec2 temp = pool.popVec2();
qA.set(aA);
qB.set(aB);
// Compute the effective masses.
Rot.mulToOutUnsafe(qA, temp.set(m_localAnchorA).subLocal(m_localCenterA), rA);
Rot.mulToOutUnsafe(qB, temp.set(m_localAnchorB).subLocal(m_localCenterB), rB);
d.set(cB).addLocal(rB).subLocal(cA).subLocal(rA);
// Point to line constraint
{
Rot.mulToOut(qA, m_localYAxisA, m_ay);
m_sAy = Vec2.cross(temp.set(d).addLocal(rA), m_ay);
m_sBy = Vec2.cross(rB, m_ay);
m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy;
if (m_mass > 0.0f) {
m_mass = 1.0f / m_mass;
}
}
// Spring constraint
m_springMass = 0.0f;
m_bias = 0.0f;
m_gamma = 0.0f;
if (m_frequencyHz > 0.0f) {
Rot.mulToOut(qA, m_localXAxisA, m_ax);
m_sAx = Vec2.cross(temp.set(d).addLocal(rA), m_ax);
m_sBx = Vec2.cross(rB, m_ax);
float invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx;
if (invMass > 0.0f) {
m_springMass = 1.0f / invMass;
float C = Vec2.dot(d, m_ax);
// Frequency
float omega = 2.0f * MathUtils.PI * m_frequencyHz;
// Damping coefficient
float d = 2.0f * m_springMass * m_dampingRatio * omega;
// Spring stiffness
float k = m_springMass * omega * omega;
// magic formulas
float h = data.step.dt;
m_gamma = h * (d + h * k);
if (m_gamma > 0.0f) {
m_gamma = 1.0f / m_gamma;
}
m_bias = C * h * k * m_gamma;
m_springMass = invMass + m_gamma;
if (m_springMass > 0.0f) {
m_springMass = 1.0f / m_springMass;
}
}
} else {
m_springImpulse = 0.0f;
}
// Rotational motor
if (m_enableMotor) {
m_motorMass = iA + iB;
if (m_motorMass > 0.0f) {
m_motorMass = 1.0f / m_motorMass;
}
} else {
m_motorMass = 0.0f;
m_motorImpulse = 0.0f;
}
if (data.step.warmStarting) {
final Vec2 P = pool.popVec2();
// Account for variable time step.
m_impulse *= data.step.dtRatio;
m_springImpulse *= data.step.dtRatio;
m_motorImpulse *= data.step.dtRatio;
P.x = m_impulse * m_ay.x + m_springImpulse * m_ax.x;
P.y = m_impulse * m_ay.y + m_springImpulse * m_ax.y;
float LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse;
float LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse;
vA.x -= m_invMassA * P.x;
vA.y -= m_invMassA * P.y;
wA -= m_invIA * LA;
vB.x += m_invMassB * P.x;
vB.y += m_invMassB * P.y;
wB += m_invIB * LB;
pool.pushVec2(1);
} else {
m_impulse = 0.0f;
m_springImpulse = 0.0f;
m_motorImpulse = 0.0f;
}
pool.pushRot(2);
pool.pushVec2(1);
// data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
@Override
public void solveVelocityConstraints (SolverData data) {
float mA = m_invMassA, mB = m_invMassB;
float iA = m_invIA, iB = m_invIB;
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
final Vec2 temp = pool.popVec2();
final Vec2 P = pool.popVec2();
// Solve spring constraint
{
float Cdot = Vec2.dot(m_ax, temp.set(vB).subLocal(vA)) + m_sBx * wB - m_sAx * wA;
float impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse);
m_springImpulse += impulse;
P.x = impulse * m_ax.x;
P.y = impulse * m_ax.y;
float LA = impulse * m_sAx;
float LB = impulse * m_sBx;
vA.x -= mA * P.x;
vA.y -= mA * P.y;
wA -= iA * LA;
vB.x += mB * P.x;
vB.y += mB * P.y;
wB += iB * LB;
}
// Solve rotational motor constraint
{
float Cdot = wB - wA - m_motorSpeed;
float impulse = -m_motorMass * Cdot;
float oldImpulse = m_motorImpulse;
float maxImpulse = data.step.dt * m_maxMotorTorque;
m_motorImpulse = MathUtils.clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = m_motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve point to line constraint
{
float Cdot = Vec2.dot(m_ay, temp.set(vB).subLocal(vA)) + m_sBy * wB - m_sAy * wA;
float impulse = -m_mass * Cdot;
m_impulse += impulse;
P.x = impulse * m_ay.x;
P.y = impulse * m_ay.y;
float LA = impulse * m_sAy;
float LB = impulse * m_sBy;
vA.x -= mA * P.x;
vA.y -= mA * P.y;
wA -= iA * LA;
vB.x += mB * P.x;
vB.y += mB * P.y;
wB += iB * LB;
}
pool.pushVec2(2);
// data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
@Override
public boolean solvePositionConstraints (SolverData data) {
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
final Rot qA = pool.popRot();
final Rot qB = pool.popRot();
final Vec2 temp = pool.popVec2();
qA.set(aA);
qB.set(aB);
Rot.mulToOut(qA, temp.set(m_localAnchorA).subLocal(m_localCenterA), rA);
Rot.mulToOut(qB, temp.set(m_localAnchorB).subLocal(m_localCenterB), rB);
d.set(cB).subLocal(cA).addLocal(rB).subLocal(rA);
Vec2 ay = pool.popVec2();
Rot.mulToOut(qA, m_localYAxisA, ay);
float sAy = Vec2.cross(temp.set(d).addLocal(rA), ay);
float sBy = Vec2.cross(rB, ay);
float C = Vec2.dot(d, ay);
float k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy;
float impulse;
if (k != 0.0f) {
impulse = -C / k;
} else {
impulse = 0.0f;
}
final Vec2 P = pool.popVec2();
P.x = impulse * ay.x;
P.y = impulse * ay.y;
float LA = impulse * sAy;
float LB = impulse * sBy;
cA.x -= m_invMassA * P.x;
cA.y -= m_invMassA * P.y;
aA -= m_invIA * LA;
cB.x += m_invMassB * P.x;
cB.y += m_invMassB * P.y;
aB += m_invIB * LB;
pool.pushVec2(3);
pool.pushRot(2);
// data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
// data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
return MathUtils.abs(C) <= Settings.linearSlop;
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./gdx/src/com/badlogic/gdx/graphics/g3d/particles/renderers/ParticleControllerRenderer.java | /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.particles.renderers;
import com.badlogic.gdx.graphics.g3d.particles.ParticleController;
import com.badlogic.gdx.graphics.g3d.particles.ParticleControllerComponent;
import com.badlogic.gdx.graphics.g3d.particles.batches.ParticleBatch;
/** It's a {@link ParticleControllerComponent} which determines how the particles are rendered. It's the base class of every
* particle renderer.
* @author Inferno */
public abstract class ParticleControllerRenderer<D extends ParticleControllerRenderData, T extends ParticleBatch<D>>
extends ParticleControllerComponent {
protected T batch;
protected D renderData;
protected ParticleControllerRenderer () {
}
protected ParticleControllerRenderer (D renderData) {
this.renderData = renderData;
}
@Override
public void update () {
batch.draw(renderData);
}
@SuppressWarnings("unchecked")
public boolean setBatch (ParticleBatch<?> batch) {
if (isCompatible(batch)) {
this.batch = (T)batch;
return true;
}
return false;
}
public abstract boolean isCompatible (ParticleBatch<?> batch);
@Override
public void set (ParticleController particleController) {
super.set(particleController);
if (renderData != null) renderData.controller = controller;
}
}
| /*******************************************************************************
* Copyright 2011 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.
******************************************************************************/
package com.badlogic.gdx.graphics.g3d.particles.renderers;
import com.badlogic.gdx.graphics.g3d.particles.ParticleController;
import com.badlogic.gdx.graphics.g3d.particles.ParticleControllerComponent;
import com.badlogic.gdx.graphics.g3d.particles.batches.ParticleBatch;
/** It's a {@link ParticleControllerComponent} which determines how the particles are rendered. It's the base class of every
* particle renderer.
* @author Inferno */
public abstract class ParticleControllerRenderer<D extends ParticleControllerRenderData, T extends ParticleBatch<D>>
extends ParticleControllerComponent {
protected T batch;
protected D renderData;
protected ParticleControllerRenderer () {
}
protected ParticleControllerRenderer (D renderData) {
this.renderData = renderData;
}
@Override
public void update () {
batch.draw(renderData);
}
@SuppressWarnings("unchecked")
public boolean setBatch (ParticleBatch<?> batch) {
if (isCompatible(batch)) {
this.batch = (T)batch;
return true;
}
return false;
}
public abstract boolean isCompatible (ParticleBatch<?> batch);
@Override
public void set (ParticleController particleController) {
super.set(particleController);
if (renderData != null) renderData.controller = controller;
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-bullet/jni/swig-src/softbody/com/badlogic/gdx/physics/bullet/softbody/SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t.java | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.softbody;
public class SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t {
private transient long swigCPtr;
protected SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t (long cPtr, @SuppressWarnings("unused") boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t () {
swigCPtr = 0;
}
protected static long getCPtr (SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.badlogic.gdx.physics.bullet.softbody;
public class SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t {
private transient long swigCPtr;
protected SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t (long cPtr, @SuppressWarnings("unused") boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t () {
swigCPtr = 0;
}
protected static long getCPtr (SWIGTYPE_p_btAlignedObjectArrayT_btSoftBody__Cluster_p_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/pooling/IOrderedStack.java | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.pooling;
/** This stack assumes that when you push 'n' items back, you're pushing back the last 'n' items popped.
* @author Daniel
*
* @param <E> */
public interface IOrderedStack<E> {
/** Returns the next object in the pool
* @return */
public E pop ();
/** Returns the next 'argNum' objects in the pool in an array
* @param argNum
* @return an array containing the next pool objects in items 0-argNum. Array length and uniqueness not guaranteed. */
public E[] pop (int argNum);
/** Tells the stack to take back the last 'argNum' items
* @param argNum */
public void push (int argNum);
}
| /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.pooling;
/** This stack assumes that when you push 'n' items back, you're pushing back the last 'n' items popped.
* @author Daniel
*
* @param <E> */
public interface IOrderedStack<E> {
/** Returns the next object in the pool
* @return */
public E pop ();
/** Returns the next 'argNum' objects in the pool in an array
* @param argNum
* @return an array containing the next pool objects in items 0-argNum. Array length and uniqueness not guaranteed. */
public E[] pop (int argNum);
/** Tells the stack to take back the last 'argNum' items
* @param argNum */
public void push (int argNum);
}
| -1 |
libgdx/libgdx | 7,309 | Use empty Audio implementations on Android and iOS when audio is disabled | Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | obigu | "2023-12-27T22:37:18Z" | "2023-12-28T19:29:00Z" | 2b691f735f4b167c062f8f68186a6d7237d3d855 | 7f682a7921a47f0da858508f6b6fd58426dd05d7 | Use empty Audio implementations on Android and iOS when audio is disabled. Since `Audio` interfaces for each backend were created some time ago we can use them to free implementations from the responsibility of handling `disabledAudio` configurations. This PR moves the `disabledAudio` config check to a single point in the application (in the `createAudio()` method to be precise) where it decides whether to return the default `Audio` implementation or the `Disabled` one (dummy).
The main advantages is that it reduces the implementations complexity and coupling to Configuration also preventing potential mistakes such as the ones present on `OALIOSAudio` in which actions on the OpenAL instance are executed when `disabledAudio` is set to `true` (such as `didBecomeActive()` or `willEnterForeground()` methods.
I can't think of a scenario in which this breaks anything but users will always have the chance to override `createAudio()` to make it behave as preferred.
The other backends have different approaches and there's room for improvement there but I've chosen to limit the scope of this PR to just Android and iOS. | ./extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/dynamics/joints/JointDef.java | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.dynamics.joints;
import org.jbox2d.dynamics.Body;
/** Joint definitions are used to construct joints.
* @author Daniel Murphy */
public class JointDef {
public JointDef (JointType type) {
this.type = type;
userData = null;
bodyA = null;
bodyB = null;
collideConnected = false;
}
/** The joint type is set automatically for concrete joint types. */
public JointType type;
/** Use this to attach application specific data to your joints. */
public Object userData;
/** The first attached body. */
public Body bodyA;
/** The second attached body. */
public Body bodyB;
/** Set this flag to true if the attached bodies should collide. */
public boolean collideConnected;
}
| /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package org.jbox2d.dynamics.joints;
import org.jbox2d.dynamics.Body;
/** Joint definitions are used to construct joints.
* @author Daniel Murphy */
public class JointDef {
public JointDef (JointType type) {
this.type = type;
userData = null;
bodyA = null;
bodyB = null;
collideConnected = false;
}
/** The joint type is set automatically for concrete joint types. */
public JointType type;
/** Use this to attach application specific data to your joints. */
public Object userData;
/** The first attached body. */
public Body bodyA;
/** The second attached body. */
public Body bodyB;
/** Set this flag to true if the attached bodies should collide. */
public boolean collideConnected;
}
| -1 |