com.badlogic.gdx.utils.Pools Java Examples

The following examples show how to use com.badlogic.gdx.utils.Pools. 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 File: ControllerMenuStage.java    From gdx-controllerutils with Apache License 2.0 6 votes vote down vote up
protected boolean fireEventOnActor(Actor actor, InputEvent.Type type, int pointer, Actor related) {
    if (actor == null || !isActorFocusable(actor) || !isActorHittable(actor))
        return false;

    InputEvent event = Pools.obtain(InputEvent.class);
    event.setType(type);
    event.setStage(this);
    event.setRelatedActor(related);
    event.setPointer(pointer);
    event.setButton(pointer);
    event.setStageX(0);
    event.setStageY(0);

    actor.fire(event);

    boolean handled = event.isHandled();
    Pools.free(event);
    return handled;
}
 
Example #2
Source File: Scene2dUtils.java    From gdx-vfx with Apache License 2.0 6 votes vote down vote up
public static void simulateClickGlobal(Actor actor, int button, int pointer, float stageX, float stageY) {
    InputEvent event = Pools.obtain(InputEvent.class);
    event.setStage(actor.getStage());
    event.setRelatedActor(actor);
    event.setTarget(actor);
    event.setStageX(stageX);
    event.setStageY(stageY);
    event.setButton(button);
    event.setPointer(pointer);

    event.setType(InputEvent.Type.touchDown);
    actor.notify(event, false);
    event.setType(InputEvent.Type.touchUp);
    actor.notify(event, false);

    Pools.free(event);
}
 
Example #3
Source File: DiceHeroes.java    From dice-heroes with GNU General Public License v3.0 6 votes vote down vote up
Array<RewardResult> applyLevelResult(BaseLevelDescription level, LevelResult result, boolean isWin) {
    Array<RewardResult> results = new Array<RewardResult>();
    if (isWin) {
        boolean isFirstPass = !userData.isPassed(level);
        Array<Reward> rewards = isFirstPass ? level.passRewards : level.confirmRewards;
        for (Reward reward : rewards) {
            results.add(reward.apply(userData));
        }
        userData.addLevelToPassed(level);
    }
    for (Die die : result.addedExperience.keys()) {
        die.exp += result.addedExperience.get(die, 0);
    }
    Config.achievements.fire(
        EventType.endLevel,
        Pools.obtain(EndLevelEvent.class).level(level).win(isWin).result(result)
    );
    for (Item item : result.viewer.earnedItems.keys()) {
        int count = result.viewer.earnedItems.get(item, 0);
        userData.incrementItemCount(item, count);
        Config.achievements.fire(EventType.earnItem, Pools.obtain(EarnEvent.class).item(item).count(count));
    }
    userData.setPotions(result.viewer.potions);
    save();
    return results;
}
 
Example #4
Source File: GameServicesMultiplayer.java    From dice-heroes with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void loadInvitations(InvitationBuffer invitations) {
    ObjectSet<String> tmp = Pools.obtain(ObjectSet.class);
    tmp.addAll(invites);
    invites.clear();
    for (Invitation invitation : invitations) {
        invites.add(invitation.getInvitationId());
        if (!tmp.contains(invitation.getInvitationId())) {
            showInvitation(invitation);
        }
    }
    tmp.clear();
    Pools.free(tmp);
    Gdx.app.postRunnable(new Runnable() {
        @Override public void run() {
            invitesDispatcher.setState(invites.size);
        }
    });
}
 
Example #5
Source File: ProgressBar.java    From cocos-ui-libgdx with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the progress bar position, rounded to the nearest step size and clamped to the minumum and maximim values.
 * {@link #clamp(float)} can be overidden to allow values outside of the progress bars min/max range.
 *
 * @return false if the value was not changed because the progress bar already had the value or it was canceled by a listener.
 */
public boolean setValue(float value) {
    value = snap(clamp(Math.round(value / stepSize) * stepSize));
    float oldValue = this.value;
    if (value == oldValue) {
        return false;
    }
    float oldVisualValue = getVisualValue();
    this.value = value;
    ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
    boolean cancelled = fire(changeEvent);
    if (cancelled) {
        this.value = oldValue;
    } else if (animateDuration > 0) {
        animateFromValue = oldVisualValue;
        animateTime = animateDuration;
    }
    Pools.free(changeEvent);
    return !cancelled;
}
 
Example #6
Source File: SeekBar.java    From gdx-texture-packer-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Called by {@link SeekBarModel}. Notifies when underlying model value has changed and text field and slider must update.
 * Typically there is no need to call this method manually.
 * @param fireEvent if true then {@link ChangeListener.ChangeEvent} will be fired
 */
public void notifyValueChanged (boolean updateTextField, boolean updateSlider, boolean fireEvent) {
    if (updateTextField) {
        VisValidatableTextField textField = getTextField();
        int cursor = textField.getCursorPosition();
        textField.setCursorPosition(0);
        this.setListenTextChangeEvents(false);
        textField.setText(model.prepareTextValue());
        this.setListenTextChangeEvents(true);
        textField.setCursorPosition(cursor);
    }

    if (updateSlider) {
        VisSlider slider = getSlider();
        this.setListenSliderChangeEvents(false);
        slider.setValue(model.prepareSliderValue());
        this.setListenSliderChangeEvents(true);
    }

    if (fireEvent) {
        ChangeListener.ChangeEvent changeEvent = Pools.obtain(ChangeListener.ChangeEvent.class);
        fire(changeEvent);
        Pools.free(changeEvent);
    }
}
 
Example #7
Source File: Scene2dUtils.java    From gdx-texture-packer-gui with Apache License 2.0 6 votes vote down vote up
public static void simulateClickGlobal(Actor actor, int button, int pointer, float stageX, float stageY) {
    InputEvent event = Pools.obtain(InputEvent.class);
    event.setStage(actor.getStage());
    event.setRelatedActor(actor);
    event.setTarget(actor);
    event.setStageX(stageX);
    event.setStageY(stageY);
    event.setButton(button);
    event.setPointer(pointer);

    event.setType(InputEvent.Type.touchDown);
    actor.notify(event, false);
    event.setType(InputEvent.Type.touchUp);
    actor.notify(event, false);

    Pools.free(event);
}
 
Example #8
Source File: EventUtils.java    From riiablo with Apache License 2.0 6 votes vote down vote up
public static boolean click(Button button) {
  if (button.isDisabled()) return false;
  InputEvent event = Pools.obtain(InputEvent.class);
  event.setType(InputEvent.Type.touchDown);
  event.setStage(button.getStage());
  event.setStageX(0);
  event.setStageY(0);
  event.setPointer(0);
  event.setButton(Input.Buttons.LEFT);
  event.setListenerActor(button);
  button.fire(event);

  event.setType(InputEvent.Type.touchUp);
  button.fire(event);
  Pools.free(event);
  return true;
}
 
Example #9
Source File: TabbedPane.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
/** Sends a ChangeEvent, with this TabbedPane as the target, to each registered listener. This method is called each time there
 * is a change to the selected index. */
protected void fireStateChanged () {
	ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
	changeEvent.setBubbles(false);
	fire(changeEvent);
	Pools.free(changeEvent);
}
 
Example #10
Source File: Actions3d.java    From Scene3d with Apache License 2.0 5 votes vote down vote up
/** Returns a new or pooled action of the specified type. */
static public <T extends Action3d> T action3d (Class<T> type) {
        Pool<T> pool = Pools.get(type);
        T action = pool.obtain();
        action.setPool(pool);
        return action;
}
 
Example #11
Source File: ChainLight.java    From box2dlights with Apache License 2.0 5 votes vote down vote up
@Override
public boolean contains(float x, float y) {
	// fast fail
	if (!this.chainLightBounds.contains(x, y))
		return false;
	// actual check
	FloatArray vertices = Pools.obtain(FloatArray.class);
	vertices.clear();
	
	for (int i = 0; i < rayNum; i++) {
		vertices.addAll(mx[i], my[i]);
	}
	for (int i = rayNum - 1; i > -1; i--) {
		vertices.addAll(startX[i], startY[i]);
	}
	
	int intersects = 0;
	for (int i = 0; i < vertices.size; i += 2) {
		float x1 = vertices.items[i];
		float y1 = vertices.items[i + 1];
		float x2 = vertices.items[(i + 2) % vertices.size];
		float y2 = vertices.items[(i + 3) % vertices.size];
		if (((y1 <= y && y < y2) || (y2 <= y && y < y1)) &&
				x < ((x2 - x1) / (y2 - y1) * (y - y1) + x1))
			intersects++;
	}
	boolean result = (intersects & 1) == 1;

	Pools.free(vertices);
	return result;
}
 
Example #12
Source File: ChainLight.java    From box2dlights with Apache License 2.0 5 votes vote down vote up
/**
 * Draws a polygon, using ray start and end points as vertices
 */
public void debugRender(ShapeRenderer shapeRenderer) {
	shapeRenderer.setColor(Color.YELLOW);
	FloatArray vertices = Pools.obtain(FloatArray.class);
	vertices.clear();
	for (int i = 0; i < rayNum; i++) {
		vertices.addAll(mx[i], my[i]);
	}
	for (int i = rayNum - 1; i > -1; i--) {
		vertices.addAll(startX[i], startY[i]);
	}
	shapeRenderer.polygon(vertices.shrink());
	Pools.free(vertices);
}
 
Example #13
Source File: ChannelBar.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
private void updateValueFromTouch (float x) {
	int newValue = (int) (x / BasicColorPicker.BAR_WIDTH * maxValue / sizes.scaleFactor);
	setValue(newValue);

	ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
	fire(changeEvent);
	Pools.free(changeEvent);
}
 
Example #14
Source File: Palette.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
private void updateValueFromTouch (float touchX, float touchY) {
	int newV = (int) (touchX / BasicColorPicker.PALETTE_SIZE * maxValue / sizes.scaleFactor);
	int newS = (int) (touchY / BasicColorPicker.PALETTE_SIZE * maxValue / sizes.scaleFactor);

	setValue(newS, newV);

	ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
	fire(changeEvent);
	Pools.free(changeEvent);
}
 
Example #15
Source File: VerticalChannelBar.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
private void updateValueFromTouch (float y) {
	int newValue = (int) (y / BasicColorPicker.PALETTE_SIZE * maxValue / sizes.scaleFactor);
	setValue(newValue);

	ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
	fire(changeEvent);
	Pools.free(changeEvent);
}
 
Example #16
Source File: Spinner.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
/**
 * Called by {@link SpinnerModel}. Notifies when underlying model value has changed and spinner text field must updated.
 * Typically there is no need to call this method manually.
 * @param fireEvent if true then {@link ChangeListener.ChangeEvent} will be fired
 */
public void notifyValueChanged (boolean fireEvent) {
	VisValidatableTextField textField = getTextField();
	int cursor = textField.getCursorPosition();
	textField.setCursorPosition(0);
	textField.setText(model.getText());
	textField.setCursorPosition(cursor);

	if (fireEvent) {
		ChangeListener.ChangeEvent changeEvent = Pools.obtain(ChangeListener.ChangeEvent.class);
		fire(changeEvent);
		Pools.free(changeEvent);
	}
}
 
Example #17
Source File: Audio.java    From riiablo with Apache License 2.0 5 votes vote down vote up
static Instance obtain(AssetDescriptor descriptor, Object delegate, long id) {
  Instance instance = Pools.obtain(Instance.class);
  instance.descriptor = descriptor;
  instance.stream   = delegate instanceof Music;
  instance.delegate = delegate;
  instance.id       = id;
  return instance;
}
 
Example #18
Source File: RenderedConsole.java    From riiablo with Apache License 2.0 5 votes vote down vote up
public void render(Batch b) {
  if (!visible || font == null) return;

  b.draw(modalBackground, 0, consoleY - 4, clientWidth, consoleHeight + 4);

  final int x = 2;
  String inputContents = in.getContents();
  GlyphLayout glyphs = font.draw(b, BUFFER_PREFIX + inputContents, x, bufferY - 2);
  b.draw(cursorTexture, x, bufferY, clientWidth, 2);
  if (showCaret) {
    final int caret = in.getCaretPosition();
    if (caret != in.length()) {
      glyphs.setText(font, BUFFER_PREFIX + inputContents.substring(0, caret));
    }

    b.draw(cursorTexture, x + glyphs.width, consoleY - 2, 2, textHeight);
  }
  Pools.free(glyphs);

  final float outputOffset = scrollOffset * lineHeight;
  if (outputOffset < outputHeight) {
    // offsets output to always appear that it starts at top of console window
    scrollOffset = Math.max(scrollOffset, scrollOffsetMin);
  }

  float position = outputY;
  final int outputSize = OUTPUT.size;
  if (scrollOffset > outputSize) {
    scrollOffset = outputSize;
    position += ((scrollOffsetMin - scrollOffset) * lineHeight);
  }

  for (int i = scrollOffset - 1; i >= 0; i--) {
    if (position > clientHeight) break;
    String line = OUTPUT.get(i);
    font.draw(b, line, x, position);
    position += lineHeight;
  }
}
 
Example #19
Source File: ParticleActor.java    From dice-heroes with GNU General Public License v3.0 5 votes vote down vote up
@Override public void draw(Batch batch, float parentAlpha) {
    effect.setPosition(getX(), getY());
    Color c = getColor();
    batch.setColor(c.r, c.g, c.b, c.a * parentAlpha);
    effect.draw(batch, Gdx.graphics.getDeltaTime());
    if (effect.isComplete()) {
        ChangeListener.ChangeEvent event = Pools.obtain(ChangeListener.ChangeEvent.class);
        fire(event);
        Pools.free(event);
    }
}
 
Example #20
Source File: UserData.java    From dice-heroes with GNU General Public License v3.0 5 votes vote down vote up
public void addDie(Die description) {
    if (ownedDice.contains(description, true))
        throw new IllegalArgumentException("Already have die " + description);
    ownedDice.insert(0, description);
    dieAdded.dispatch(description);

    Config.achievements.fire(EventType.obtainDie, Pools.obtain(DieEvent.class).die(description));
}
 
Example #21
Source File: AStar.java    From dice-heroes with GNU General Public License v3.0 5 votes vote down vote up
private static Node getNode(int x, int y) {
    Node n = nodes.get(x, y);
    if (n == null) {
        n = Pools.obtain(Node.class).set(x, y);
        nodes.put(x, y, n);
    }
    return n;
}
 
Example #22
Source File: SpawnController.java    From dice-heroes with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void autoPlace() {
    if (placed.size > 0) {
        ObjectSet<Creature> tmp = Pools.obtain(ObjectSet.class);
        tmp.addAll(placed);
        for (Creature c : tmp) {
            removeFromPlaced(c);
        }
        tmp.clear();
        Pools.free(tmp);
    }
    Array<Grid2D.Coordinate> coordinates = Pools.obtain(Array.class);
    Set<Map.Entry<Grid2D.Coordinate, Fraction>> spawns = world.level.getElements(LevelElementType.spawn);
    for (Map.Entry<Grid2D.Coordinate, Fraction> e : spawns) {
        if (e.getValue() == world.viewer.fraction) {
            coordinates.add(e.getKey());
        }
    }
    coordinates.shuffle();
    int usedCount = Math.min(creatures.size, coordinates.size);
    Array<Creature> toPlace = Pools.obtain(Array.class);
    toPlace.addAll(creatures);
    toPlace.shuffle();
    toPlace.truncate(usedCount);
    for (Creature creature : toPlace) {
        Grid2D.Coordinate coordinate = coordinates.pop();
        place(creature, coordinate.x(), coordinate.y());
    }
    toPlace.clear();
    coordinates.clear();
    Pools.free(toPlace);
    Pools.free(coordinates);
}
 
Example #23
Source File: HighlightTextArea.java    From vis-ui with Apache License 2.0 4 votes vote down vote up
@Override
protected void calculateOffsets () {
	super.calculateOffsets();
	if (chunkUpdateScheduled == false) return;
	chunkUpdateScheduled = false;
	highlights.sort();
	renderChunks.clear();

	String text = getText();

	Pool<GlyphLayout> layoutPool = Pools.get(GlyphLayout.class);
	GlyphLayout layout = layoutPool.obtain();
	boolean carryHighlight = false;
	for (int lineIdx = 0, highlightIdx = 0; lineIdx < linesBreak.size; lineIdx += 2) {
		int lineStart = linesBreak.items[lineIdx];
		int lineEnd = linesBreak.items[lineIdx + 1];
		int lineProgress = lineStart;
		float chunkOffset = 0;

		for (; highlightIdx < highlights.size; ) {
			Highlight highlight = highlights.get(highlightIdx);
			if (highlight.getStart() > lineEnd) {
				break;
			}

			if (highlight.getStart() == lineProgress || carryHighlight) {
				renderChunks.add(new Chunk(text.substring(lineProgress, Math.min(highlight.getEnd(), lineEnd)), highlight.getColor(), chunkOffset, lineIdx));
				lineProgress = Math.min(highlight.getEnd(), lineEnd);

				if (highlight.getEnd() > lineEnd) {
					carryHighlight = true;
				} else {
					carryHighlight = false;
					highlightIdx++;
				}
			} else {
				//protect against overlapping highlights
				boolean noMatch = false;
				while (highlight.getStart() <= lineProgress) {
					highlightIdx++;
					if (highlightIdx >= highlights.size) {
						noMatch = true;
						break;
					}
					highlight = highlights.get(highlightIdx);
					if (highlight.getStart() > lineEnd) {
						noMatch = true;
						break;
					}
				}
				if (noMatch) break;
				renderChunks.add(new Chunk(text.substring(lineProgress, highlight.getStart()), defaultColor, chunkOffset, lineIdx));
				lineProgress = highlight.getStart();
			}

			Chunk chunk = renderChunks.peek();
			layout.setText(style.font, chunk.text);
			chunkOffset += layout.width;
			//current highlight needs to be applied to next line meaning that there is no other highlights that can be applied to currently parsed line
			if (carryHighlight) break;
		}

		if (lineProgress < lineEnd) {
			renderChunks.add(new Chunk(text.substring(lineProgress, lineEnd), defaultColor, chunkOffset, lineIdx));
		}
	}

	maxAreaWidth = 0;
	for (String line : text.split("\\n")) {
		layout.setText(style.font, line);
		maxAreaWidth = Math.max(maxAreaWidth, layout.width + 30);
	}

	layoutPool.free(layout);
	updateScrollLayout();
}
 
Example #24
Source File: MenuItem.java    From vis-ui with Apache License 2.0 4 votes vote down vote up
void fireChangeEvent () {
	ChangeListener.ChangeEvent changeEvent = Pools.obtain(ChangeListener.ChangeEvent.class);
	fire(changeEvent);
	Pools.free(changeEvent);
}
 
Example #25
Source File: Entity.java    From riiablo with Apache License 2.0 4 votes vote down vote up
public void drawDebugStatus(PaletteIndexedBatch batch, ShapeRenderer shapes) {
  float x = screen.x;
  float y = screen.y;
  if (animation != null && isSelectable()) animation.drawDebug(shapes, x, y);

  shapes.setColor(Color.WHITE);
  DebugUtils.drawDiamond(shapes, x, y, Tile.SUBTILE_WIDTH, Tile.SUBTILE_HEIGHT);
  //shapes.ellipse(x - Tile.SUBTILE_WIDTH50, y - Tile.SUBTILE_HEIGHT50, Tile.SUBTILE_WIDTH, Tile.SUBTILE_HEIGHT);

  final float R = 32;
  shapes.setColor(Color.RED);
  shapes.line(x, y, x + MathUtils.cos(angle) * R, y + MathUtils.sin(angle) * R);

  if (animation != null) {
    int numDirs = animation.getNumDirections();
    float rounded = Direction.snapToDirection(angle, numDirs);
    shapes.setColor(Color.GREEN);
    shapes.line(x, y, x + MathUtils.cos(rounded) * R * 0.5f, y + MathUtils.sin(rounded) * R * 0.5f);
  }

  shapes.end();
  batch.begin();
  batch.setShader(null);
  StringBuilder builder = new StringBuilder(64)
      .append(classname).append('\n')
      .append(token).append(' ').append(type.MODE[mode]).append(' ').append(WCLASS[wclass]).append('\n');
  if (animation != null) {
    builder
        .append(StringUtils.leftPad(Integer.toString(animation.getFrame()), 2))
        .append('/')
        .append(StringUtils.leftPad(Integer.toString(animation.getNumFramesPerDir() - 1), 2))
        .append(' ')
        .append(animation.getFrameDelta())
        .append('\n');
  }
  appendToStatus(builder);
  GlyphLayout layout = Riiablo.fonts.consolas12.draw(batch, builder.toString(), x, y - Tile.SUBTILE_HEIGHT50, 0, Align.center, false);
  Pools.free(layout);
  batch.end();
  batch.setShader(Riiablo.shader);
  shapes.begin(ShapeRenderer.ShapeType.Line);
}
 
Example #26
Source File: VisTextArea.java    From vis-ui with Apache License 2.0 4 votes vote down vote up
@Override
protected void calculateOffsets () {
	super.calculateOffsets();
	if (!this.text.equals(lastText)) {
		this.lastText = text;
		BitmapFont font = style.font;
		float maxWidthLine = this.getWidth()
				- (style.background != null ? style.background.getLeftWidth() + style.background.getRightWidth() : 0);
		linesBreak.clear();
		int lineStart = 0;
		int lastSpace = 0;
		char lastCharacter;
		Pool<GlyphLayout> layoutPool = Pools.get(GlyphLayout.class);
		GlyphLayout layout = layoutPool.obtain();
		for (int i = 0; i < text.length(); i++) {
			lastCharacter = text.charAt(i);
			if (lastCharacter == ENTER_DESKTOP || lastCharacter == ENTER_ANDROID) {
				linesBreak.add(lineStart);
				linesBreak.add(i);
				lineStart = i + 1;
			} else {
				lastSpace = (continueCursor(i, 0) ? lastSpace : i);
				layout.setText(font, text.subSequence(lineStart, i + 1));
				if (layout.width > maxWidthLine && softwrap) {
					if (lineStart >= lastSpace) {
						lastSpace = i - 1;
					}
					linesBreak.add(lineStart);
					linesBreak.add(lastSpace + 1);
					lineStart = lastSpace + 1;
					lastSpace = lineStart;
				}
			}
		}
		layoutPool.free(layout);
		// Add last line
		if (lineStart < text.length()) {
			linesBreak.add(lineStart);
			linesBreak.add(text.length());
		}
		showCursor();
	}
}
 
Example #27
Source File: AStar.java    From dice-heroes with GNU General Public License v3.0 4 votes vote down vote up
private static void cleanUp() {
    for (Node n : nodes.values()) {
        Pools.free(n);
    }
    nodes.clear();
}