com.badlogic.gdx.Gdx Java Examples

The following examples show how to use com.badlogic.gdx.Gdx. 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: CharData.java    From riiablo with Apache License 2.0 6 votes vote down vote up
/**
   * FIXME: originally worked as an aggregate call on {@link #cursorToBelt(int, int)} and
   *        {@link #beltToCursor(int)}, and while that worked fine programically to pass the
   *        assertions within {@link ItemData}, {@link ItemData.LocationListener#onChanged}
   *        was being called out of order for setting the cursor, causing the cursor to be unset
   *        within the UI immediately after being changed.
   */
//  @Override
  public void swapBeltItem(int i) {
    if (DEBUG_ITEMS) Gdx.app.log(TAG, "swapBeltItem");

    // #beltToCursor(int)
    Item newCursorItem = itemData.getItem(i);

    // #cursorToBelt(int,int)
    Item item = itemData.getItem(itemData.cursor);
    item.gridX = newCursorItem.gridX;
    item.gridY = newCursorItem.gridY;
    itemData.setLocation(item, Location.BELT);
    itemData.cursor = ItemData.INVALID_ITEM;

    itemData.pickup(i);
  }
 
Example #2
Source File: GameSceneState.java    From Entitas-Java with MIT License 6 votes vote down vote up
@Override
public void loadResources() {
    this.skinManager = engine.getManager(SMGUIManager.class);
    this.assetsManager = engine.getManager(BaseAssetsManager.class);
    guiFactory = new GuiFactory(assetsManager, skin);
    bodyBuilder =  new BodyBuilder();
    this.stage = new Stage();
    stage.clear();
    stage.getViewport().update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
    Gdx.input.setInputProcessor(stage);
    Gdx.app.log("Menu", "LoadResources");

    assetsManager.loadTextureAtlas(SPRITE_ATLAS);
    assetsManager.finishLoading();

}
 
Example #3
Source File: GdxScreen.java    From libGDX-Path-Editor with Apache License 2.0 6 votes vote down vote up
public GdxScreen(GdxApp gdxApp, int stageW, int stageH, int canvasW, int canvasH) {
	super(gdxApp);
	this.screenW = stageW;
	this.screenH = stageH;
	
	camera = new Camera(canvasW, canvasH);
	camera.position.x = (int)(screenW / 2);
	camera.position.y = (int)(screenH / 2);
	
	stage = new Stage(stageW, stageH, false);
	stage.setCamera(camera);
	
	bgDrawer = new BGDrawer();
	
	inputMultiplexer = new InputMultiplexer();
	inputMultiplexer.addProcessor(stage);
	inputMultiplexer.addProcessor(new InputHandler());
	Gdx.input.setInputProcessor(inputMultiplexer);
}
 
Example #4
Source File: StateMachineTest.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
@Override
public void render () {
	float delta = Gdx.graphics.getDeltaTime();
	elapsedTime += delta;

	// Update time
	GdxAI.getTimepiece().update(delta);

	if (elapsedTime > 0.8f) {
		// Update Bob and his wife
		bob.update(elapsedTime);
		elsa.update(elapsedTime);

		// Dispatch any delayed messages
		MessageManager.getInstance().update();

		elapsedTime = 0;
	}
}
 
Example #5
Source File: WndAndroidTextInput.java    From shattered-pixel-dungeon with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void destroy() {
	super.destroy();
	if (textInput != null){
		((AndroidApplication)Gdx.app).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				//make sure we remove the edit text and soft keyboard
				((ViewGroup) textInput.getParent()).removeView(textInput);

				InputMethodManager imm = (InputMethodManager)((AndroidApplication)Gdx.app).getSystemService(Activity.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(((AndroidGraphics)Gdx.app.getGraphics()).getView().getWindowToken(), 0);

				//Soft keyboard sometimes triggers software buttons, so make sure to reassert immersive
				ShatteredPixelDungeon.updateSystemUI();

				textInput = null;
			}
		});
	}
}
 
Example #6
Source File: DefaultSceneScreen.java    From bladecoder-adventure-engine with Apache License 2.0 6 votes vote down vote up
@Override
public void show() {
	final InputMultiplexer multiplexer = new InputMultiplexer();
	multiplexer.addProcessor(stage);
	multiplexer.addProcessor(inputProcessor);
	Gdx.input.setInputProcessor(multiplexer);

	if (getWorld().isDisposed()) {
		try {
			getWorld().load();
		} catch (Exception e) {
			EngineLogger.error("ERROR LOADING GAME", e);

			dispose();
			Gdx.app.exit();
		}
	}

	getWorld().setListener(worldListener);
	getWorld().resume();
}
 
Example #7
Source File: GpgsClient.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
private File findFileByNameSync(String name) throws IOException {
    // escape some chars (') see : https://developers.google.com/drive/v3/web/search-parameters#fn1
    List<File> files = GApiGateway.drive.files().list().setSpaces("appDataFolder").setQ("name='" + name + "'")
            .execute().getFiles();
    if (files.size() > 1) {
        File snapshotFile = null;
        for (File file : files) {
            if (file.getMimeType().equals("application/vnd.google-play-games.snapshot")) {
                // Search for snapshot files and choose the first found one
                snapshotFile = file;
                break;
            }
        }
        if (snapshotFile == null)
            Gdx.app.error(TAG, "Multiple files with name " + name + " exists. No snapshot file found");
        else
            Gdx.app.log(TAG, "Multiple files with name " + name + " exists. Choose snapshot file with ID:  " + snapshotFile.getId());
        return snapshotFile;
    } else if (files.size() < 1) {
        return null;
    } else {
        return files.get(0);
    }
}
 
Example #8
Source File: LevelLoader.java    From ud406 with MIT License 6 votes vote down vote up
private static void loadNonPlatformEntities(Level level, JSONArray nonPlatformObjects) {
    for (Object o : nonPlatformObjects) {
        JSONObject item = (JSONObject) o;

        final Vector2 imagePosition = extractXY(item);

        if (item.get(Constants.LEVEL_IMAGENAME_KEY).equals(Constants.POWERUP_SPRITE)) {
            final Vector2 powerupPosition = imagePosition.add(Constants.POWERUP_CENTER);
            Gdx.app.log(TAG, "Loaded a powerup at " + powerupPosition);
            level.getPowerups().add(new Powerup(powerupPosition));
        } else if (item.get(Constants.LEVEL_IMAGENAME_KEY).equals(Constants.STANDING_RIGHT)) {
            final Vector2 gigaGalPosition = imagePosition.add(Constants.GIGAGAL_EYE_POSITION);
            Gdx.app.log(TAG, "Loaded GigaGal at " + gigaGalPosition);
            level.setGigaGal(new GigaGal(gigaGalPosition, level));
        } else if (item.get(Constants.LEVEL_IMAGENAME_KEY).equals(Constants.EXIT_PORTAL_SPRITE_1)) {
            final Vector2 exitPortalPosition = imagePosition.add(Constants.EXIT_PORTAL_CENTER);
            Gdx.app.log(TAG, "Loaded the exit portal at " + exitPortalPosition);
            level.setExitPortal(new ExitPortal(exitPortalPosition));
        }

    }
}
 
Example #9
Source File: DialogDrawables.java    From skin-composer with MIT License 6 votes vote down vote up
private void newDrawableDialog() {
    main.getDialogFactory().showDialogLoading(() -> {
        String defaultPath = "";

        if (main.getProjectData().getLastDrawablePath() != null) {
            FileHandle fileHandle = new FileHandle(main.getProjectData().getLastDrawablePath());
            if (fileHandle.parent().exists()) {
                defaultPath = main.getProjectData().getLastDrawablePath();
            }
        }

        String[] filterPatterns = null;
        if (!Utils.isMac()) {
            filterPatterns = new String[]{"*.png", "*.jpg", "*.jpeg", "*.bmp", "*.gif"};
        }

        List<File> files = main.getDesktopWorker().openMultipleDialog("Choose drawable file(s)...", defaultPath, filterPatterns, "Image files");
        if (files != null && files.size() > 0) {
            Gdx.app.postRunnable(() -> {
                drawablesSelected(files);
            });
        }
    });
}
 
Example #10
Source File: Ssao.java    From uracer-kotd with Apache License 2.0 6 votes vote down vote up
public Ssao (int fboWidth, int fboHeight, Quality quality) {
	Gdx.app.log("SsaoProcessor", "Quality profile = " + quality.toString());
	float oscale = quality.scale;

	// maps
	occlusionMap = new PingPongBuffer((int)((float)fboWidth * oscale), (int)((float)fboHeight * oscale), Format.RGBA8888, false);

	// shaders
	shMix = ShaderLoader.fromFile("screenspace", "ssao/mix");
	shSsao = ShaderLoader.fromFile("ssao/ssao", "ssao/ssao");

	// blur
	blur = new Blur(occlusionMap.width, occlusionMap.height);
	blur.setType(BlurType.Gaussian5x5b);
	blur.setPasses(2);

	createRandomField(16, 16, Format.RGBA8888);
	// enableDebug();
}
 
Example #11
Source File: GlobalConfiguration.java    From SIFTrain with MIT License 6 votes vote down vote up
public static void storeConfiguration() {
    Preferences prefs = Gdx.app.getPreferences("sif_train_config");
    prefs.putInteger("offset", offset);
    prefs.putInteger("input_offset", inputOffset);
    prefs.putInteger("song_vol", songVolume);
    prefs.putInteger("feedback_vol", feedbackVolume);
    prefs.putString("path_to_beatmaps", pathToBeatmaps);
    prefs.putBoolean("play_hint_sounds", playHintSounds);
    prefs.putInteger("note_speed", noteSpeed);
    prefs.putInteger("overall_difficulty", overallDifficulty);
    prefs.putInteger("sorting_mode", sortMode);
    prefs.putInteger("random_mode", randomMode);
    prefs.putInteger("sorting_order", sortOrder);
    prefs.putInteger("sync_mode", syncMode);
    prefs.flush();
}
 
Example #12
Source File: TxtParser.java    From riiablo with Apache License 2.0 6 votes vote down vote up
private TxtParser(BufferedReader in) {
  this.in = in;

  try {
    line = in.readLine();
    columns = StringUtils.splitPreserveAllTokens(line, '\t');
    if (DEBUG_COLS) Gdx.app.debug(TAG, "cols=" + Arrays.toString(columns));

    ids = new ObjectIntMap<>();
    for (int i = 0; i < columns.length; i++) {
      String key = columns[i].toLowerCase();
      if (!ids.containsKey(key)) ids.put(key, i);
    }
  } catch (Throwable t) {
    throw new GdxRuntimeException("Couldn't read txt", t);
  }
}
 
Example #13
Source File: MainMenu.java    From Radix with MIT License 6 votes vote down vote up
public void init() {
    if (!initialized) {
        camera = new OrthographicCamera();
        batch = new SpriteBatch();
        batch.setTransformMatrix(RadixClient.getInstance().getHudCamera().combined);
        batch.setTransformMatrix(camera.combined);
        mmButtonTexture = new Texture(Gdx.files.internal("textures/gui/mmBtn.png"));

        buttonFont = new BitmapFont();

        resize();
        rerender();

        initialized = true;
    }
}
 
Example #14
Source File: GLTFDemo.java    From gdx-gltf with Apache License 2.0 6 votes vote down vote up
private void load(FileHandle glFile){
	Gdx.app.log(TAG, "loading " + glFile.name());
	
	lastFileName = glFile.path();
	
	if(USE_ASSET_MANAGER){
		assetManager.load(lastFileName, SceneAsset.class);
		assetManager.finishLoading();
		rootModel = assetManager.get(lastFileName, SceneAsset.class);
	}else{
		if(glFile.extension().equalsIgnoreCase("glb")){
			rootModel = new GLBLoader().load(glFile);
		}else if(glFile.extension().equalsIgnoreCase("gltf")){
			rootModel = new GLTFLoader().load(glFile);
		}
	}
	
	load();
	
	Gdx.app.log(TAG, "loaded " + glFile.path());
	
	new GLTFInspector().inspect(rootModel);
}
 
Example #15
Source File: GameplayScreen.java    From ud406 with MIT License 6 votes vote down vote up
@Override
public void render(float delta) {
    level.update(delta);
    chaseCam.update(delta);
    gameplayViewport.apply();
    Gdx.gl.glClearColor(
            Constants.BACKGROUND_COLOR.r,
            Constants.BACKGROUND_COLOR.g,
            Constants.BACKGROUND_COLOR.b,
            Constants.BACKGROUND_COLOR.a);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(gameplayViewport.getCamera().combined);
    batch.begin();
    level.render(batch);

    batch.end();

}
 
Example #16
Source File: GameplayScreen.java    From ud406 with MIT License 6 votes vote down vote up
@Override
public void render(float delta) {

    level.update(delta);
    chaseCam.update(delta);


    Gdx.gl.glClearColor(
            Constants.BACKGROUND_COLOR.r,
            Constants.BACKGROUND_COLOR.g,
            Constants.BACKGROUND_COLOR.b,
            Constants.BACKGROUND_COLOR.a);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);


    level.render(batch);
    if (onMobile()) {
        onscreenControls.render(batch);
    }
    hud.render(batch, level.getGigaGal().getLives(), level.getGigaGal().getAmmo(), level.score);
    renderLevelEndOverlays(batch);
}
 
Example #17
Source File: ActuatorEntity.java    From Entitas-Java with MIT License 6 votes vote down vote up
public ActuatorEntity replaceParticleEffectActuator(ParticleEffect effect,
		boolean autoStart, float locaPosX, float locaPosY) {
	ParticleEffectActuator component = (ParticleEffectActuator) recoverComponent(ActuatorComponentsLookup.ParticleEffectActuator);
	if (component == null) {
		component = new ParticleEffectActuator(effect, autoStart, locaPosX,
				locaPosY);
	} else {
		component.particleEffect = effect;
		component.actuator = (indexOwner) -> {
			GameEntity owner = Indexed.getInteractiveEntity(indexOwner);
			RigidBody rc = owner.getRigidBody();
			Transform transform = rc.body.getTransform();
			effect.setPosition(transform.getPosition().x + locaPosX,
					transform.getPosition().y + locaPosY);
			effect.update(Gdx.graphics.getDeltaTime());
			if (autoStart && effect.isComplete())
				effect.start();
		};
	}
	replaceComponent(ActuatorComponentsLookup.ParticleEffectActuator,
			component);
	return this;
}
 
Example #18
Source File: GameLayout.java    From Klooni1010 with GNU General Public License v3.0 6 votes vote down vote up
private void calculate() {
    screenWidth = Gdx.graphics.getWidth();
    screenHeight = Gdx.graphics.getHeight();

    // Widths
    marginWidth = screenWidth * 0.05f;
    availableWidth = screenWidth - marginWidth * 2f;

    // Heights
    logoHeight = screenHeight * 0.10f;
    scoreHeight = screenHeight * 0.15f;
    boardHeight = screenHeight * 0.50f;
    pieceHolderHeight = screenHeight * 0.25f;

    shopCardHeight = screenHeight * 0.15f;
}
 
Example #19
Source File: GameOverScreen.java    From Bomberman_libGdx with MIT License 5 votes vote down vote up
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1f);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.act(delta);
    stage.draw();
}
 
Example #20
Source File: LightMap.java    From box2dlights with Apache License 2.0 5 votes vote down vote up
public void render() {

		boolean needed = rayHandler.lightRenderedLastFrame > 0;


		if (lightMapDrawingDisabled)
			return;
		frameBuffer.getColorBufferTexture().bind(0);

		// at last lights are rendered over scene
		if (rayHandler.shadows) {
			final Color c = rayHandler.ambientLight;
			ShaderProgram shader = shadowShader;
			if (RayHandler.isDiffuse) {
				shader = diffuseShader;
				shader.begin();
				rayHandler.diffuseBlendFunc.apply();
				shader.setUniformf("ambient", c.r, c.g, c.b, c.a);
			} else {
				shader.begin();
				rayHandler.shadowBlendFunc.apply();
				shader.setUniformf("ambient", c.r * c.a, c.g * c.a,
						c.b * c.a, 1f - c.a);
			}
		//	shader.setUniformi("u_texture", 0);
			lightMapMesh.render(shader, GL20.GL_TRIANGLE_FAN);
			shader.end();
		} else if (needed) {
			rayHandler.simpleBlendFunc.apply();
			withoutShadowShader.begin();
		//	withoutShadowShader.setUniformi("u_texture", 0);
			lightMapMesh.render(withoutShadowShader, GL20.GL_TRIANGLE_FAN);
			withoutShadowShader.end();
		}

		Gdx.gl20.glDisable(GL20.GL_BLEND);
	}
 
Example #21
Source File: GameJoltClient.java    From gdx-gamesvcs with Apache License 2.0 5 votes vote down vote up
@Override
public boolean unlockAchievement(String achievementId) {
    if (trophyMapper == null) {
        Gdx.app.log(GAMESERVICE_ID, "Cannot unlock achievement: No mapper for trophy ids provided.");
        return false;
    }

    if (!isSessionActive())
        return false;

    Integer trophyId = trophyMapper.mapToGsId(achievementId);

    // no board available or not connected
    if (trophyId == null)
        return false;

    Map<String, String> params = new HashMap<String, String>();
    addGameIDUserNameUserToken(params);
    params.put("trophy_id", String.valueOf(trophyId));

    final Net.HttpRequest http = buildJsonRequest("trophies/add-achieved/", params);
    if (http == null)
        return false;

    Gdx.net.sendHttpRequest(http, new NoOpResponseListener());

    return true;
}
 
Example #22
Source File: MainMenuScreen.java    From Klooni1010 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void render(float delta) {
    Klooni.theme.glClearBackground();
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(Math.min(Gdx.graphics.getDeltaTime(), minDelta));
    stage.draw();

    if (Gdx.input.isKeyJustPressed(Input.Keys.BACK)) {
        Gdx.app.exit();
    }
}
 
Example #23
Source File: CursorManager.java    From vis-ui with Apache License 2.0 5 votes vote down vote up
/** Restores currently used cursor to default one. */
public static void restoreDefaultCursor () {
	if (systemCursorAsDefault) {
		Gdx.graphics.setSystemCursor(defaultSystemCursor);
	} else {
		Gdx.graphics.setCursor(defaultCursor);
	}
}
 
Example #24
Source File: ParseTreeTest.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
@Override
public Actor createActor (Skin skin) {
	Reader reader = null;
	try {
		reader = Gdx.files.internal("data/dog.tree").reader();
		BehaviorTreeParser<Dog> parser = new BehaviorTreeParser<Dog>(BehaviorTreeParser.DEBUG_HIGH);
		BehaviorTree<Dog> tree = parser.parse(reader, new Dog("Buddy"));
		treeViewer = createTreeViewer(tree.getObject().name, tree, true, skin);

		return new ScrollPane(treeViewer, skin);
	} finally {
		StreamUtils.closeQuietly(reader);
	}
}
 
Example #25
Source File: ClientAdapter.java    From Cubes with MIT License 5 votes vote down vote up
private boolean splashScreen() {
  Log.debug("Showing splash screen");
  glClear();
  
  SplashMenu splashMenu = new SplashMenu();
  Graphics.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
  splashMenu.resize(Graphics.GUI_WIDTH, Graphics.GUI_HEIGHT);
  splashMenu.render();
  Log.debug("Splash screen rendered");
  
  return true;
}
 
Example #26
Source File: OnDoubleClickLmlAttribute.java    From gdx-texture-packer-gui with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final LmlParser parser, final LmlTag tag, final Actor actor, final String rawAttributeData) {
    final ActorConsumer<?, Params> action = parser.parseAction(rawAttributeData, tmpParams);
    if (action == null) {
        parser.throwError("Could not find action for: " + rawAttributeData + " with actor: " + actor);
    }
    actor.addListener(new ClickListener(0) {
        private boolean firstClickCaught = false;
        private long lastClickTime = 0;

        @Override
        public void clicked(final InputEvent event, final float x, final float y) {
            long currentEventTime = Gdx.input.getCurrentEventTime();
            long deltaTime = currentEventTime - lastClickTime;
            lastClickTime = currentEventTime;

            if (!firstClickCaught) {
                firstClickCaught = true;
            } else {
                if (deltaTime < SECOND_CLICK_TIME) {
                    firstClickCaught = false;

                    tmpParams.actor = actor;
                    tmpParams.x = x;
                    tmpParams.y = y;
                    tmpParams.stageX = event.getStageX();
                    tmpParams.stageY = event.getStageY();
                    action.consume(tmpParams);
                    tmpParams.reset();
                }
            }
        }
    });
}
 
Example #27
Source File: EntityFileReader.java    From Norii with Apache License 2.0 5 votes vote down vote up
public static void loadUnitStatsInMemory() {
	if (!statsLoaded) {
		final Json json = new Json();
		final EntityData[] unitStats = json.fromJson(EntityData[].class, Gdx.files.internal(UNIT_STATS_FILE_LOCATION));
		for (int i = 0; i < unitStats.length; i++) {
			final EntityData data = unitStats[i];
			unitData.put(data.getID(), data);
		}
		statsLoaded = true;
	}
}
 
Example #28
Source File: BallScreen.java    From ud405 with MIT License 5 votes vote down vote up
@Override
public void render(float delta) {
    viewport.apply();

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);

    renderer.setProjectionMatrix(viewport.getCamera().combined);
    ball.update(delta);

    renderer.begin(ShapeType.Filled);
    ball.render(renderer);
    renderer.end();
}
 
Example #29
Source File: GdxIOSAppTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    PowerMockito.mockStatic(NatJ.class);
    IOSApplication application = Mockito.mock(IOSApplication.class);
    Mockito.when(application.getType()).thenReturn(Application.ApplicationType.iOS);
    Gdx.app = application;
    GdxFIRApp.setThrowFailureByDefault(false);
}
 
Example #30
Source File: IOSGDXTextPrompt.java    From gdx-dialogs with Apache License 2.0 5 votes vote down vote up
@Override
public GDXTextPrompt dismiss() {
    if (alertView == null) {
        throw new RuntimeException(GDXTextPrompt.class.getSimpleName() + " has not been build. Use build() before dismiss().");
    }
    Gdx.app.debug(GDXDialogsVars.LOG_TAG, IOSGDXTextPrompt.class.getSimpleName() + " dismissed.");
    alertView.dismiss(0, false);
    return this;
}