Java Code Examples for com.badlogic.gdx.utils.GdxRuntimeException

The following examples show how to use com.badlogic.gdx.utils.GdxRuntimeException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Mundus   Source File: MG3dModelLoader.java    License: Apache License 2.0 6 votes vote down vote up
private int parseType(String type) {
    if (type.equals("TRIANGLES")) {
        return GL20.GL_TRIANGLES;
    } else if (type.equals("LINES")) {
        return GL20.GL_LINES;
    } else if (type.equals("POINTS")) {
        return GL20.GL_POINTS;
    } else if (type.equals("TRIANGLE_STRIP")) {
        return GL20.GL_TRIANGLE_STRIP;
    } else if (type.equals("LINE_STRIP")) {
        return GL20.GL_LINE_STRIP;
    } else {
        throw new GdxRuntimeException("Unknown primitive type '" + type
                + "', should be one of triangle, trianglestrip, line, linestrip, lineloop or point");
    }
}
 
Example 2
Source Project: gdx-ai   Source File: Box2dSteeringTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void setRandomNonOverlappingPosition (Box2dSteeringEntity character, Array<Box2dSteeringEntity> others,
	float minDistanceFromBoundary) {
	int maxTries = Math.max(100, others.size * others.size); 
	SET_NEW_POS:
	while (--maxTries >= 0) {
		int x = MathUtils.random((int)container.stageWidth);
		int y = MathUtils.random((int)container.stageHeight);
		float angle = MathUtils.random(-MathUtils.PI, MathUtils.PI);
		character.body.setTransform(pixelsToMeters(x), pixelsToMeters(y), angle);
		for (int i = 0; i < others.size; i++) {
			Box2dSteeringEntity other = (Box2dSteeringEntity)others.get(i);
			if (character.getPosition().dst(other.getPosition()) <= character.getBoundingRadius() + other.getBoundingRadius()
				+ minDistanceFromBoundary) continue SET_NEW_POS;
		}
		return;
	}
	throw new GdxRuntimeException("Probable infinite loop detected");
}
 
Example 3
Source Project: riiablo   Source File: COFD2.java    License: Apache License 2.0 6 votes vote down vote up
public static COFD2 loadFromStream(InputStream in) {
  try {
    int i = 0;
    Array<Entry> entries = new Array<>(1024);
    while (in.available() > 0) {
      Entry entry = new Entry(in);
      entries.add(entry);
      if (DEBUG_ENTRIES) Gdx.app.debug(TAG, i++ + ": " + entry.toString());
      if (entry.header1 != -1 || entry.header2 != 0 || entry.header3 != -1) {
        Gdx.app.error(TAG, "Invalid entry headers: " + entry);
      }
    }

    return new COFD2(entries);
  } catch (Throwable t) {
    throw new GdxRuntimeException("Couldn't load D2 from stream.", t);
  } finally {
    StreamUtils.closeQuietly(in);
  }
}
 
Example 4
Source Project: Mundus   Source File: ShaderUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Compiles and links shader.
 *
 * @param vertexShader
 *            path to vertex shader
 * @param fragmentShader
 *            path to fragment shader
 *
 * @return compiled shader program
 */
public static ShaderProgram compile(String vertexShader, String fragmentShader) {
    String vert;
    String frag;

    if (Gdx.app.getType() == Application.ApplicationType.WebGL) {
        vert = Gdx.files.internal(vertexShader).readString();
        frag = Gdx.files.internal(fragmentShader).readString();
    } else {
        vert = Gdx.files.classpath(vertexShader).readString();
        frag = Gdx.files.classpath(fragmentShader).readString();
    }

    ShaderProgram program = new ShaderProgram(vert, frag);
    if (!program.isCompiled()) {
        throw new GdxRuntimeException(program.getLog());
    }

    return program;
}
 
Example 5
Source Project: gdx-ai   Source File: BehaviorTreeParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void parse (char[] data, int offset, int length) {
	debug = btParser.debugLevel > BehaviorTreeParser.DEBUG_NONE;
	root = null;
	clear();
	super.parse(data, offset, length);

	// Pop all task from the stack and check their minimum number of children
	popAndCheckMinChildren(0);

	Subtree<E> rootTree = subtrees.get("");
	if (rootTree == null) throw new GdxRuntimeException("Missing root tree");
	root = rootTree.rootTask;
	if (root == null) throw new GdxRuntimeException("The tree must have at least the root task");

	clear();
}
 
Example 6
Source Project: libgdx-snippets   Source File: VertexAttributeArray.java    License: MIT License 6 votes vote down vote up
private int getTypeSize(int type) {

		switch (type) {

			case GL_BYTE:
			case GL_UNSIGNED_BYTE:
				return 1;

			case GL_SHORT:
			case GL_UNSIGNED_SHORT:
				return 2;

			case GL_INT:
			case GL_UNSIGNED_INT:
			case GL_FLOAT:
				return 4;

			default:
				throw new GdxRuntimeException("Unsupported vertex attribute type!");
		}
	}
 
Example 7
Source Project: gdx-proto   Source File: HeadlessG3dModelLoader.java    License: Apache License 2.0 6 votes vote down vote up
public ModelData parseModel (FileHandle handle) {
	JsonValue json = reader.parse(handle);
	ModelData model = new ModelData();
	JsonValue version = json.require("version");
	model.version[0] = version.getShort(0);
	model.version[1] = version.getShort(1);
	if (model.version[0] != VERSION_HI || model.version[1] != VERSION_LO)
		throw new GdxRuntimeException("Model version not supported");

	model.id = json.getString("id", "");
	parseMeshes(model, json);
	//parseMaterials(model, json, handle.parent().path());
	parseNodes(model, json);
	parseAnimations(model, json);
	return model;
}
 
Example 8
Source Project: gdx-skineditor   Source File: Skin.java    License: Apache License 2.0 6 votes vote down vote up
public <T> T get(String name, Class<T> type) {
	if (name == null)
		throw new IllegalArgumentException("name cannot be null.");
	if (type == null)
		throw new IllegalArgumentException("type cannot be null.");

	if (type == Drawable.class)
		return (T) getDrawable(name);
	if (type == TextureRegion.class)
		return (T) getRegion(name);
	if (type == NinePatch.class)
		return (T) getPatch(name);
	if (type == Sprite.class)
		return (T) getSprite(name);

	ObjectMap<String, Object> typeResources = resources.get(type);
	if (typeResources == null)
		throw new GdxRuntimeException("No " + type.getName() + " registered with name: " + name);
	Object resource = typeResources.get(name);
	if (resource == null)
		throw new GdxRuntimeException("No " + type.getName() + " registered with name: " + name);
	return (T) resource;
}
 
Example 9
Source Project: beatoraja   Source File: SkinTextFont.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void prepareText(String text) {
       if(preparedFonts != null) {
       	return;
       }
       if(font != null) {
           font.dispose();
           font = null;
       }
       
       try {
           parameter.characters = text;
           font = generator.generateFont(parameter);
           layout = new GlyphLayout(font, "");        	
   	} catch (GdxRuntimeException e) {
   		Logger.getGlobal().warning("Font準備失敗 : " + text + " - " + e.getMessage());
   	}
}
 
Example 10
Source Project: Mundus   Source File: MG3dModelLoader.java    License: Apache License 2.0 6 votes vote down vote up
public ModelData parseModel(FileHandle handle) {
    JsonValue json = reader.parse(handle);
    ModelData model = new ModelData();
    JsonValue version = json.require("version");
    model.version[0] = version.getShort(0);
    model.version[1] = version.getShort(1);
    if (model.version[0] != VERSION_HI || model.version[1] != VERSION_LO)
        throw new GdxRuntimeException("Model version not supported");

    model.id = json.getString("id", "");
    parseMeshes(model, json);
    parseMaterials(model, json, handle.parent().path());
    parseNodes(model, json);
    parseAnimations(model, json);
    return model;
}
 
Example 11
Source Project: gdx-ai   Source File: ResumeVsJoinTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void setRandomNonOverlappingPosition (SteeringActor character, Array<? extends SteeringActor> others,
	float minDistanceFromBoundary) {
	int maxTries = Math.max(100, others.size * others.size);
	SET_NEW_POS:
	while (--maxTries >= 0) {
		character.setPosition(MathUtils.random(stage.getWidth()), MathUtils.random(stage.getHeight()), Align.center);
		character.getPosition().set(character.getX(Align.center), character.getY(Align.center));
		for (int i = 0; i < others.size; i++) {
			SteeringActor other = (SteeringActor)others.get(i);
			if (character.getPosition().dst(other.getPosition()) <= character.getBoundingRadius() + other.getBoundingRadius()
				+ minDistanceFromBoundary) continue SET_NEW_POS;
		}
		return;
	}
	throw new GdxRuntimeException("Probable infinite loop detected");
}
 
Example 12
Source Project: ashley   Source File: ImmutableArrayTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void forbiddenRemoval () {
	Array<Integer> array = new Array<Integer>();
	ImmutableArray<Integer> immutable = new ImmutableArray<Integer>(array);

	for (int i = 0; i < 10; ++i) {
		array.add(i);
	}

	boolean thrown = false;

	try {
		immutable.iterator().remove();
	} catch (GdxRuntimeException e) {
		thrown = true;
	}

	assertEquals(true, thrown);
}
 
Example 13
Source Project: bladecoder-adventure-engine   Source File: SpineRenderer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String[] getInternalAnimations(AnimationDesc anim) {
	try {
		retrieveSource(anim.source, ((SpineAnimationDesc) anim).atlas);
	} catch (GdxRuntimeException e) {
		sourceCache.remove(anim.source);
		Array<String> dependencies = EngineAssetManager.getInstance().getDependencies(getFileName(anim.source));
		if (dependencies.size > 0)
			dependencies.removeIndex(dependencies.size - 1);
		return new String[0];
	}

	Array<Animation> animations = ((SkeletonCacheEntry) sourceCache.get(anim.source)).skeleton.getData()
			.getAnimations();

	String[] result = new String[animations.size];

	for (int i = 0; i < animations.size; i++) {
		Animation a = animations.get(i);
		result[i] = a.getName();
	}

	return result;
}
 
Example 14
Source Project: gdx-vfx   Source File: LmlUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void saveDtdSchema(final LmlParser lmlParser, final FileHandle file) {
    try {
        final Writer appendable = file.writer(false, "UTF-8");
        final boolean strict = lmlParser.isStrict();
        lmlParser.setStrict(false); // Temporary setting to non-strict to generate as much tags as possible.
        Dtd.saveSchema(lmlParser, appendable);
        appendable.close();
        lmlParser.setStrict(strict);
    } catch (final Exception exception) {
        throw new GdxRuntimeException("Unable to save DTD schema.", exception);
    }
}
 
Example 15
Source Project: mini2Dx   Source File: Mini2DxOpenALMusic.java    License: Apache License 2.0 5 votes vote down vote up
public void play () {
	if (audio.noDevice) return;
	if (sourceID == -1) {
		sourceID = audio.obtainSource(true);
		if (sourceID == -1) return;

		audio.music.add(this);

		if (buffers == null) {
			buffers = BufferUtils.createIntBuffer(bufferCount);
			alGenBuffers(buffers);
			int errorCode = alGetError();
			if (errorCode != AL_NO_ERROR)
				throw new GdxRuntimeException("Unable to allocate audio buffers. AL Error: " + errorCode);
		}
		alSourcei(sourceID, AL_LOOPING, AL_FALSE);
		setPan(pan, volume);

		boolean filled = false; // Check if there's anything to actually play.
		for (int i = 0; i < bufferCount; i++) {
			int bufferID = buffers.get(i);
			if (!fill(bufferID)) break;
			filled = true;
			alSourceQueueBuffers(sourceID, bufferID);
		}
		if (!filled && onCompletionListener != null) onCompletionListener.onCompletion(this);

		if (alGetError() != AL_NO_ERROR) {
			stop();
			return;
		}
	}
	if (!isPlaying) {
		alSourcePlay(sourceID);
		isPlaying = true;
	}
}
 
Example 16
Source Project: riiablo   Source File: Label.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void draw(Batch batch, float a) {
  if (batch instanceof PaletteIndexedBatch) {
    draw((PaletteIndexedBatch) batch, a);
  } else {
    throw new GdxRuntimeException("Not supported");
  }
}
 
Example 17
Source Project: mini2Dx   Source File: Mini2DxMp3.java    License: Apache License 2.0 5 votes vote down vote up
public Sound (Mini2DxOpenALAudio audio, FileHandle file) {
	super(audio);
	if (audio.noDevice) return;
	ByteArrayOutputStream output = new ByteArrayOutputStream(4096);

	Bitstream bitstream = new Bitstream(file.read());
	MP3Decoder decoder = new MP3Decoder();

	try {
		OutputBuffer outputBuffer = null;
		int sampleRate = -1, channels = -1;
		while (true) {
			Header header = bitstream.readFrame();
			if (header == null) break;
			if (outputBuffer == null) {
				channels = header.mode() == Header.SINGLE_CHANNEL ? 1 : 2;
				outputBuffer = new OutputBuffer(channels, false);
				decoder.setOutputBuffer(outputBuffer);
				sampleRate = header.getSampleRate();
			}
			try {
				decoder.decodeFrame(header, bitstream);
			} catch (Exception ignored) {
				// JLayer's decoder throws ArrayIndexOutOfBoundsException sometimes!?
			}
			bitstream.closeFrame();
			output.write(outputBuffer.getBuffer(), 0, outputBuffer.reset());
		}
		bitstream.close();
		setup(output.toByteArray(), channels, sampleRate);
	} catch (Throwable ex) {
		throw new GdxRuntimeException("Error reading audio data.", ex);
	}
}
 
Example 18
public static void bundleToFile( String fileName, Bundle bundle ) throws IOException{
	try {
		bundleToStream(getFileHandle( fileName ).write(false), bundle);
	} catch (GdxRuntimeException e){
		//game classes expect an IO exception, so wrap the GDX exception in that
		throw new IOException(e);
	}
}
 
Example 19
Source Project: Mundus   Source File: EditorTerrainShader.java    License: Apache License 2.0 5 votes vote down vote up
public EditorTerrainShader() {
    String vertexShader = "\n#define PICKER\n" + Gdx.files.classpath(VERTEX_SHADER).readString();
    String fragmentShader = "\n#define PICKER\n" + Gdx.files.classpath(FRAGMENT_SHADER).readString();

    program = new ShaderProgram(vertexShader, fragmentShader);
    if (!program.isCompiled()) {
        throw new GdxRuntimeException(program.getLog());
    }
}
 
Example 20
Source Project: Cubes   Source File: LogMenu.java    License: MIT License 5 votes vote down vote up
public void refresh() {
  FileHandle fileHandle = Gdx.files.absolute(FileLogWriter.file.getAbsolutePath());
  String string = "";
  try {
    string = fileHandle.readString();
  } catch (GdxRuntimeException e) {
    Log.error("Failed to refresh log menu", e);
  }
  label.setText(string);
  resize(Graphics.GUI_WIDTH, Graphics.GUI_HEIGHT);
}
 
Example 21
Source Project: gdx-ai   Source File: BehaviorTreeParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected <E> void exit (DefaultBehaviorTreeReader<E> reader) {
	if (reader.subtreeName == null)
		throw new GdxRuntimeException(this.name + ": the name has not been specified");
	reader.switchToNewTree(reader.subtreeName);
	reader.subtreeName = null;
}
 
Example 22
Source Project: gdx-pd   Source File: PdAudioBakery.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add a new baking task.
 * @param patchFile patch file to bake.
 * @param array destination array to write to.
 * @param sampleRate sample rate to use.
 * @param time destination duration.
 */
public void addTask(FileHandle patchFile, String array, int sampleRate, float time){
	if(bakingThread != null){
		throw new GdxRuntimeException("addTask should only be called before baking process.");
	}
	Baking baking = new Baking();
	baking.patchFile = patchFile;
	baking.array = array;
	baking.sampleRate = sampleRate;
	baking.time = time;
	pendingBakings.add(baking);
}
 
Example 23
Source Project: gdx-gltf   Source File: AnimationControllerHack.java    License: Apache License 2.0 5 votes vote down vote up
/** Apply a single animation to the {@link ModelInstance} and update the it to reflect the changes. */
@Override
protected void applyAnimation (final Animation animation, final float time) {
	if (applying) throw new GdxRuntimeException("Call end() first");
	applyAnimationPlus(null, (Pool<Transform>)null, 1.f, animation, time);
	if(calculateTransforms) target.calculateTransforms();
}
 
Example 24
Source Project: gdx-pd   Source File: MidiEvent.java    License: Apache License 2.0 5 votes vote down vote up
public static final MidiEvent parseEvent(long tick, long delta, InputStream in) throws IOException
{
    in.mark(1);

    int id = in.read();
    if(!verifyIdentifier(id))
    {
        in.reset();
    }

    if(sType >= 0x8 && sType <= 0xE)
    {
        return ChannelEvent.parseChannelEvent(tick, delta, sType, sChannel, in);
    }
    else if(sId == 0xFF)
    {
        return MetaEvent.parseMetaEvent(tick, delta, in);
    }
    else if(sId == 0xF0 || sId == 0xF7)
    {
        VariableLengthInt size = new VariableLengthInt(in);
        byte[] data = new byte[size.getValue()];
        in.read(data);
        return new SystemExclusiveEvent(sId, tick, delta, data);
    }
    else
    {
    	throw new GdxRuntimeException("Unable to handle status byte, skipping: " + sId);
    }

}
 
Example 25
Source Project: gdx-gltf   Source File: PBRCommon.java    License: Apache License 2.0 5 votes vote down vote up
public static void checkVertexAttributes(Renderable renderable){
	final int numVertexAttributes = renderable.meshPart.mesh.getVertexAttributes().size();
	final int maxVertexAttribs = getCapability(GL20.GL_MAX_VERTEX_ATTRIBS);
	if(numVertexAttributes > maxVertexAttribs){
		throw new GdxRuntimeException("too many vertex attributes : " + numVertexAttributes + " > " + maxVertexAttribs);
	}
}
 
Example 26
Source Project: riiablo   Source File: StringTBL.java    License: Apache License 2.0 5 votes vote down vote up
public static StringTBL loadFromStream(InputStream in) {
  try {
    Header header = new Header(in);
    if (DEBUG) Gdx.app.debug(TAG, header.toString());
    if (header.version != 1)
      throw new GdxRuntimeException("Unsupported version: " + (header.version & 0xFF));

    short[] indexes = new short[header.numElements];
    ByteBuffer.wrap(IOUtils.readFully(in, header.numElements * 2))
        .order(ByteOrder.LITTLE_ENDIAN)
        .asShortBuffer()
        .get(indexes);
    if (DEBUG) Gdx.app.debug(TAG, "indexes = " + Arrays.toString(indexes));

    HashTable hashTable = new HashTable(header, in);
    if (DEBUG) Gdx.app.debug(TAG, hashTable.toString());

    // TODO: Support other languages
    final int dataSize = header.endIndex - header.startIndex;
    char[] text = new char[dataSize];
    Reader reader = new InputStreamReader(in, "US-ASCII");
    IOUtils.readFully(reader, text);

    return new StringTBL(header, indexes, hashTable, text);
  } catch (Throwable t) {
    throw new GdxRuntimeException("Couldn't load StringTBL from stream.", t);
  } finally {
    StreamUtils.closeQuietly(in);
  }
}
 
Example 27
Source Project: gdx-proto   Source File: NetServer.java    License: Apache License 2.0 5 votes vote down vote up
public NetServer() {
	clientMap = new ObjectMap<>();
	server = new Server(NetManager.writeBufferSize, NetManager.objectBufferSize);
	NetManager.registerKryoClasses(server.getKryo());
	try {
		server.bind(NetManager.tcpPort, NetManager.udpPort);
		server.start();
		server.addListener(createListener(simulateLag));
		Log.debug("server is listening at: " + NetManager.host + ":" + NetManager.tcpPort);
	} catch (IOException e) {
		Log.error(e.toString());
		throw new GdxRuntimeException(e);
	}
}
 
Example 28
Source Project: mini2Dx   Source File: Mini2DxMp3.java    License: Apache License 2.0 5 votes vote down vote up
public Sound (Mini2DxOpenALAudio audio, FileHandle file) {
	super(audio);
	if (audio.noDevice) return;
	ByteArrayOutputStream output = new ByteArrayOutputStream(4096);

	Bitstream bitstream = new Bitstream(file.read());
	MP3Decoder decoder = new MP3Decoder();

	try {
		OutputBuffer outputBuffer = null;
		int sampleRate = -1, channels = -1;
		while (true) {
			Header header = bitstream.readFrame();
			if (header == null) break;
			if (outputBuffer == null) {
				channels = header.mode() == Header.SINGLE_CHANNEL ? 1 : 2;
				outputBuffer = new OutputBuffer(channels, false);
				decoder.setOutputBuffer(outputBuffer);
				sampleRate = header.getSampleRate();
			}
			try {
				decoder.decodeFrame(header, bitstream);
			} catch (Exception ignored) {
				// JLayer's decoder throws ArrayIndexOutOfBoundsException sometimes!?
			}
			bitstream.closeFrame();
			output.write(outputBuffer.getBuffer(), 0, outputBuffer.reset());
		}
		bitstream.close();
		setup(output.toByteArray(), channels, sampleRate);
	} catch (Throwable ex) {
		throw new GdxRuntimeException("Error reading audio data.", ex);
	}
}
 
Example 29
public static Bundle bundleFromFile( String fileName ) throws IOException{
	try {
		FileHandle file = getFileHandle( fileName );
		return bundleFromStream(file.read());
	} catch (GdxRuntimeException e){
		//game classes expect an IO exception, so wrap the GDX exception in that
		throw new IOException(e);
	}
}
 
Example 30
Source Project: mini2Dx   Source File: IOSMini2DxInput.java    License: Apache License 2.0 5 votes vote down vote up
private int getFreePointer() {
	for (int i = 0; i < touchDown.length; i++) {
		if (touchDown[i] == 0)
			return i;
	}
	throw new GdxRuntimeException("Couldn't find free pointer id!");
}