================================================
FILE: .idea/vcs.xml
================================================
================================================
FILE: CONTRIBUTING
================================================
Contributing {#contributing}
============
Want to contribute? Great! First, read this page (including the small print at
the end).
# Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
# Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.
# The small print
Contributions made by corporations are covered by a different agreement than
the one above, the Software Grant and Corporate Contributor License Agreement.
================================================
FILE: ExampleGame.iml
================================================
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
================================================
FILE: app/app.iml
================================================
================================================
FILE: app/build.gradle
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.
*/
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "19.1"
defaultConfig {
applicationId "com.google.fpl.gim.examplegame"
minSdkVersion 16
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
}
}
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
dependencies {
compile group: 'junit', name: 'junit', version: '3.8'
compile 'com.android.support:appcompat-v7:21.+'
compile 'com.google.android.gms:play-services:6.1.+'
}
================================================
FILE: app/src/androidTest/java/com/google/fpl/gim/examplegame/MissionParseTest.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import com.google.fpl.gim.examplegame.utils.MissionParseException;
import com.google.fpl.gim.examplegame.utils.MissionParser;
import com.google.fpl.gim.examplegame.utils.Utils;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* Tests the functionality of mission parsing from XML.
*/
public class MissionParseTest extends TestCase {
private static final String TAG = MissionParseTest.class.getSimpleName();
private Mission mMission;
private MissionData mMissionData;
public void setUp() {
Utils.logDebug(TAG, "Setting up...");
// Set up mission data that will be used for every test case
String missionId = "Mission 1";
float lengthOfGameMinutes = 30f; // 30-minute game
float lengthOfIntervalMinutes = 1f; // 1-minute intervals
float challengePaceMinutesPerMile = 8.0f;
mMissionData = new MissionData(missionId, missionId, lengthOfGameMinutes,
lengthOfIntervalMinutes, challengePaceMinutesPerMile);
}
public void tearDown() {
Utils.logDebug(TAG, "Tearing down...");
}
/**
* Test for correct construction of a timer moment.
*/
public void testTimerMomentConstruction() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createTimerMomentXml( // [...]
"start", // Moment id.
"start", // Next moment id.
0.5); // Length of timer moment (minutes).
//
xml += createEndMissionXml(); //
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals("Mission 1", mMissionData.getMissionId());
Assert.assertEquals(1, mMissionData.getNumMoments());
Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof TimerMoment);
Assert.assertEquals("start", mMissionData.getMomentFromId("start").getNextMomentId());
}
/**
* Test for correct construction of a choice moment.
*/
public void testChoiceMomentConstruction() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createStartChoiceMomentXml( // [...]
"start", // Moment id.
0.5, // Length of choice timeout in minutes.
"Example ChoiceMoment Description", // Description of choice moment.
"choice_2"); // Id of default choice.
xml += createChoiceXml( // [...]
"fire", // Choice id.
"Example Choice Description 1", // Description of choice.
"start", // Next moment id.
true, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
"test_icon"); // Icon resource name.
//
xml += createChoiceXml( // [...]
"choice_2", // Choice id.
"Example Choice Description 2", // Description of choice.
"start", // Next moment id.
false, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
"test_icon"); // Icon resource name.
//
xml += createChoiceXml( // [...]
"choice_3", // Choice id.
"Example Choice Description 3", // Description of choice.
"start", // Next moment id.
true, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
"test_icon"); // Icon resource name.
//
xml += createEndChoiceMomentXml(); //
xml += createEndMissionXml(); //
Utils.logDebug(TAG, xml);
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals("Mission 1", mMissionData.getMissionId());
Assert.assertEquals(1, mMissionData.getNumMoments());
Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof ChoiceMoment);
ChoiceMoment choiceMoment = ((ChoiceMoment) mMissionData.getMomentFromId("start"));
Assert.assertEquals(3, choiceMoment.getMomentData().getNumChoices());
Choice choice1 = choiceMoment.getMomentData().getChoiceById("choice_2");
Assert.assertEquals("Example Choice Description 2", choice1.getDescription());
Assert.assertEquals("start", choice1.getNextMomentId());
Assert.assertEquals(false, choice1.getOutcome().weaponChargeDepleted());
Assert.assertEquals(false, choice1.getOutcome().numEnemiesDefeatedIncremented());
Assert.assertEquals("test_icon", choice1.getDrawableResourceName());
Assert.assertEquals(null, mMissionData.getMomentFromId("start").getNextMomentId());
}
/**
* Test for correct construction of an sfx moment.
*/
public void testSfxMomentConstruction() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createSfxMomentXml( // [...]
"start", // Moment id.
"start", // Next moment id.
"path/to/something"); // Path to sound effect resource.
//
xml += createEndMissionXml(); //
InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals("Mission 1", mMissionData.getMissionId());
Assert.assertEquals(1, mMissionData.getNumMoments());
Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof SfxMoment);
Assert.assertEquals("start", mMissionData.getMomentFromId("start").getNextMomentId());
}
/**
* Test for correct construction of a spoken text moment.
*/
public void testSpokenTextMomentConstruction() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createSpokenTextMomentXml( // [...]
"start", // Moment id.
"start", // Next moment id.
"Hello!"); // Text to speak out loud.
//
xml += createEndMissionXml(); //
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals("Mission 1", mMissionData.getMissionId());
Assert.assertEquals(1, mMissionData.getNumMoments());
Assert.assertEquals(true,
mMissionData.getMomentFromId("start") instanceof SpokenTextMoment);
Assert.assertEquals("start", mMissionData.getMomentFromId("start").getNextMomentId());
}
/**
* Test for correct construction of a mission with four different types of moments.
*/
public void testFourMomentConstruction() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createSpokenTextMomentXml( // [...]
"start", // Moment id.
"second", // Next moment id.
"Hello!"); // Text to speak out loud.
//
xml += createSfxMomentXml( // [...]
"second", // Moment id.
"third", // Next moment id.
"path/to/something"); // Path to sound effect resource.
//
xml += createStartChoiceMomentXml( // [...]
"third", // Moment id.
0.5, // Length of choice timeout in minutes.
"Example ChoiceMoment Description", // Description of choice moment.
"choice_2"); // Id of default choice.
xml += createChoiceXml( // [...]
"fire", // Choice id.
"Example Choice Description 1", // Description of choice.
"fourth", // Next moment id.
true, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
"test_icon"); // Icon resource name.
//
xml += createChoiceXml( // [...]
"choice_2", // Choice id.
"Example Choice Description 2", // Description of choice.
"fourth", // Next moment id.
false, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
"test_icon"); // Icon resource name.
//
xml += createEndChoiceMomentXml(); //
xml += createTimerMomentXml( // [...]
"fourth", // Moment id.
null, // Next moment id.
0.25); // Length of timer moment (minutes).
//
xml += createEndMissionXml(); //
InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals("Mission 1", mMissionData.getMissionId());
Assert.assertEquals(4, mMissionData.getNumMoments());
Moment spokenTextMoment = mMissionData.getMomentFromId("start");
Moment sfxMoment = mMissionData.getMomentFromId("second");
Moment choiceMoment = mMissionData.getMomentFromId("third");
Moment timerMoment = mMissionData.getMomentFromId("fourth");
Assert.assertEquals(true, spokenTextMoment instanceof SpokenTextMoment);
Assert.assertEquals(true, sfxMoment instanceof SfxMoment);
Assert.assertEquals(true, choiceMoment instanceof ChoiceMoment);
Assert.assertEquals(true, timerMoment instanceof TimerMoment);
SpokenTextMoment moment1 = (SpokenTextMoment) spokenTextMoment;
SfxMoment moment2 = (SfxMoment) sfxMoment;
ChoiceMoment moment3 = (ChoiceMoment) choiceMoment;
TimerMoment moment4 = (TimerMoment) timerMoment;
Assert.assertEquals("second", moment1.getNextMomentId());
Assert.assertEquals("third", moment2.getNextMomentId());
// The next ID of a ChoiceMoment is null until the user has made their choice.
Assert.assertEquals(null, moment3.getNextMomentId());
Assert.assertEquals("fourth", moment3.getMomentData().getChoices()[0].getNextMomentId());
// The final moment has a 'null' next moment.
Assert.assertEquals(null, moment4.getNextMomentId());
Assert.assertEquals(true, moment3.getMomentData().getChoiceById("fire")
.requiresChargedWeapon());
Assert.assertEquals(false, moment3.getMomentData().getChoiceById("choice_2")
.requiresChargedWeapon());
}
/**
* Test for correct error handling with a moment has an invalid 'type'.
*/
public void testMomentWithInvalidTypeErrorHandling() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createStartMomentXml( // [...]
"invalid", // Moment type is invalid.
"start"); // Moment id.
xml += createNextMomentXml("start"); // Next moment id.
xml += createLengthMinutesXml(0.25); // Length of (timer) moment in minutes.
xml += createEndMomentXml(); //
xml += createEndMissionXml(); //
InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
boolean didMissionParseFail = false;
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
didMissionParseFail = true;
}
Assert.assertEquals(true, didMissionParseFail);
}
/**
* Test for correct error handling with a moment has no 'type' attribute.
*/
public void testMomentWithNoTypeErrorHandling() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += " [...]
"id='start' >"; // Moment id. Moment type is missing.
xml += createNextMomentXml("start"); // Next moment id.
xml += createLengthMinutesXml(0.25); // Length of (timer) moment in minutes.
xml += createEndMomentXml(); //
xml += createEndMissionXml(); //
InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
boolean didMissionParseFail = false;
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
didMissionParseFail = true;
}
Assert.assertEquals(true, didMissionParseFail);
}
/*
* Test for correct behavior when a moment has no 'next_moment' attribute (signifies that this
* moment is the final moment in the mission.)
*/
public void testTimerMomentMissingNextMomentMission() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Name of mission.
xml += createStartMomentXml( // [...]
"timer", // Moment type.
"start"); // Moment id.
xml += createLengthMinutesXml(0.25); // Length of (timer) moment in minutes.
xml += createEndMomentXml(); //
xml += createEndMissionXml(); //
InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals("Mission 1", mMissionData.getMissionId());
Assert.assertEquals(1, mMissionData.getNumMoments());
Assert.assertEquals(true, mMissionData.getMomentFromId("start") instanceof TimerMoment);
Assert.assertEquals(null, mMissionData.getMomentFromId("start").getNextMomentId());
}
/**
* Test for correct reading of a mission name.
*/
public void testMissionNameConstruction() {
String xml = "";
xml += createStartMissionXml( // [...]
"", // First moment in mission.
"Name"); // Mission name.
xml += createEndMissionXml(); //
InputStream missionInputStream = new ByteArrayInputStream(xml.getBytes());
String missionName = null;
try {
missionName = MissionParser.getMissionName(missionInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals("Name", missionName);
}
/**
* Test for correct error handling for a mission with no "name" attribute.
*/
public void testMissingMissionNameHandling() {
String xml = "";
xml += " [...]
"start_id='' >"; // First moment in mission. Mission name is
// missing.
xml += createEndMissionXml(); //
InputStream missionInputStream = new ByteArrayInputStream(xml.getBytes());
boolean didMissionNameParseFail = false;
try {
MissionParser.getMissionName(missionInputStream);
} catch (MissionParseException e) {
didMissionNameParseFail = true;
}
Assert.assertEquals(true, didMissionNameParseFail);
}
/**
* Test for correct parsing of fictional progress for a SpokenText moment.
*/
public void testFictionalProgressSpokenTextMomentParsing() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createSpokenTextMomentWithFictionalProgressXML(
// [...]
"start", // Moment id.
null, // Next moment id.
"Text to speak", // Text to speak out loud.
"Fictional progress."); // Fictional progress.
//
xml += createEndMissionXml(); //
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals(1, mMissionData.getMomentFromId("start").getFictionalProgress().size());
Assert.assertEquals("Fictional progress.",
mMissionData.getMomentFromId("start").getFictionalProgress().get(0));
}
/**
* Test for correct parsing of fictional progress for a Timer moment.
*/
public void testFictionalProgressTimerMomentParsing() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createTimerMomentWithFictionalProgressXML(
// [...]
"start", // Moment id.
null, // Next moment id.
1.0, // Length of timer moment (minutes).
"Fictional progress."); // Fictional progress.
//
xml += createEndMissionXml(); //
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals(1, mMissionData.getMomentFromId("start").getFictionalProgress().size());
Assert.assertEquals("Fictional progress.",
mMissionData.getMomentFromId("start").getFictionalProgress().get(0));
}
/**
* Test for correct parsing of fictional progress for an Sfx moment.
*/
public void testFictionalProgressSfxMomentParsing() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createSfxMomentWithFictionalProgressXML(
// [...]
"start", // Moment id.
null, // Next moment id.
"path/to/something", // Path to sound effect resource.
"Fictional progress."); // Fictional progress.
//
xml += createEndMissionXml(); //
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
Assert.assertEquals(1, mMissionData.getMomentFromId("start").getFictionalProgress().size());
Assert.assertEquals("Fictional progress.",
mMissionData.getMomentFromId("start").getFictionalProgress().get(0));
}
/**
* Test for correct parsing of fictional progress for a Choice moment, and for correct parsing
* of fictional progress for Choices.
*/
public void testFictionalProgressChoiceMomentParsing() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createStartChoiceMomentWithFictionalProgressXML(
// [...]
"start", // Moment id.
1.0, // Next moment id.
"Choice Description", // Description of choice moment.
"choice_2", // Id of default choice.
"Fictional progress."); // Fictional progress.
xml += createChoiceWithFictionalProgressXML(
// [...]
"fire", // Choice id.
"Example Choice Description 1", // Description of choice.
null, // Next moment id.
true, // Whether the weapon charge should be depleted.
false, // Whether the number of enemies defeated should
// be incremented.
"Description 1", // Fictional progress.
"test_icon"); // Icon resource name.
//
xml += createChoiceXml( // [...]
"choice_2", // Choice id.
"Choice 2 description", // Description of choice.
null, // Next moment id.
false, // Whether the weapon charge should be depleted.
false, // Whether the number of enemies defeated should
// be incremented.
"test_icon"); // Icon resource name.
//
xml += createEndMomentXml(); //
xml += createEndMissionXml(); //
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
}
ChoiceMoment choiceMoment = ((ChoiceMoment) mMissionData.getMomentFromId("start"));
Choice fireChoice = choiceMoment.getMomentData().getChoiceById("fire");
Assert.assertEquals(1, fireChoice.getFictionalProgress().size());
Assert.assertEquals("Description 1", fireChoice.getFictionalProgress().get(0));
Choice choice2 = choiceMoment.getMomentData().getChoiceById("choice_2");
Assert.assertEquals(0, choice2.getFictionalProgress().size());
Assert.assertEquals(1, mMissionData.getMomentFromId("start").getFictionalProgress().size());
Assert.assertEquals("Fictional progress.",
mMissionData.getMomentFromId("start").getFictionalProgress().get(0));
}
/**
* Test for correct error handling for a fictional progress element that is empty.
*/
public void testFictionalProgressErrorHandling() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createTimerMomentWithFictionalProgressXML(
// [...]
"start", // Moment id.
null, // Next moment id.
1.0, // Length of timer moment (minutes).
""); // Empty fictional progress.
//
xml += createEndMissionXml(); //
InputStream momentInputStream = new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
boolean didMissionParseFail = false;
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
didMissionParseFail = true;
}
Assert.assertEquals(true, didMissionParseFail);
}
/**
* Test for correct error handling for a Choice that has no icon element.
*/
public void testChoiceMissingIconErrorHandling() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createStartChoiceMomentXml( // [...]
"start", // Moment id.
0.5, // Length of choice timeout in minutes.
"Example ChoiceMoment Description", // Description of choice moment.
"choice_2"); // Id of default choice.
xml += createChoiceXml( // [...]
"fire", // Choice id.
"Example Choice Description 1", // Description of choice.
"start", // Next moment id.
true, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
"test_icon"); // Icon resource name.
//
xml += createChoiceXml( // [...]
"choice_2", // Choice id.
"Example Choice Description 2", // Description of choice.
"start", // Next moment id.
false, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
null); // Missing icon element.
//
xml += createEndChoiceMomentXml(); //
xml += createEndMissionXml(); //
Utils.logDebug(TAG, xml);
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
boolean didMissionParseFail = false;
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
didMissionParseFail = true;
}
Assert.assertEquals(true, didMissionParseFail);
}
/**
* Test for correct error handling for a Choice that has an empty icon element.
*/
public void testChoiceEmptyIconErrorHandling() {
String xml = "";
xml += createStartMissionXml( // [...]
"start", // First moment in mission.
"Name"); // Mission name.
xml += createStartChoiceMomentXml( // [...]
"start", // Moment id.
0.5, // Length of choice timeout in minutes.
"Example ChoiceMoment Description", // Description of choice moment.
"choice_2"); // Id of default choice.
xml += createChoiceXml( // [...]
"fire", // Choice id.
"Example Choice Description 1", // Description of choice.
"start", // Next moment id.
true, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
"test_icon"); // Icon resource name.
//
xml += createChoiceXml( // [...]
"choice_2", // Choice id.
"Example Choice Description 2", // Description of choice.
"start", // Next moment id.
false, // Whether the weapon charge should be depleted
false, // Whether the number of enemies defeated should
// be incremented.
""); // Empty icon resource name.
//
xml += createEndChoiceMomentXml(); //
xml += createEndChoiceMomentXml(); //
xml += createEndMissionXml(); //
Utils.logDebug(TAG, xml);
InputStream momentInputStream =
new ByteArrayInputStream(xml.getBytes());
mMission = new Mission(mMissionData);
boolean didMissionParseFail = false;
try {
mMission.readMoments(momentInputStream);
} catch (MissionParseException e) {
e.printStackTrace();
didMissionParseFail = true;
}
Assert.assertEquals(true, didMissionParseFail);
}
/**
* A helper function to create an XML string representing the start of a mission.
* @param startMomentId The id of the first moment in the mission.
* @param missionName The plain text name of the mission.
* @return An XML string of the following format:
*
*
*/
private String createStartMissionXml(String startMomentId, String missionName) {
return "" +
"";
}
/**
* A helper function to create an XML string representing the end of a mission.
* @return A mission XML end-tag:
*/
private String createEndMissionXml() {
return "";
}
/**
* A helper function to create an XML string representing the start of a generic moment.
* @param momentType The type of moment to be created.
* @param momentId The unique id of this moment.
* @return An XML string of the following format:
*
*/
private String createStartMomentXml(String momentType, String momentId) {
return "";
}
/**
* A helper function to create an XML string representing the end of a moment.
* @return A moment XML end-tag:
*/
private String createEndMomentXml() {
return "";
}
/**
* A helper function to create an XML string representing a timer moment.
* @param momentId The unique id of the moment.
* @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this
* moment is the last moment in the mission.
* @param lengthMinutes The length of the timer moment in minutes.
* @return An XML string of the following format:
*
*
* [lengthMinutes]
*
*/
private String createTimerMomentXml(String momentId, String nextMomentId,
double lengthMinutes) {
String xml = "";
xml += createStartMomentXml("timer", momentId);
xml += createNextMomentXml(nextMomentId);
xml += createLengthMinutesXml(lengthMinutes);
xml += createEndMomentXml();
return xml;
}
/**
* A helper function to create an XML string representing a 'next_moment id' attribute.
* All moment types can have 'next_moment id''s, and the lack of a 'next_moment id' signifies
* that the current moment is the last moment in the mission.
* @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this
* moment is the last moment in the mission.
* @return If 'nextMomentId' is null, return an empty string. Otherwise, an XML string of the
* following format is returned:
*
*/
private String createNextMomentXml(String nextMomentId) {
if (nextMomentId == null) {
return "";
}
return "";
}
/**
* A helper function to create an XML string representing the start of a choice moment.
* @param momentId The unique id of the moment.
* @param timeoutLengthMinutes The length of time in minutes after which the default choice
* should be chosen for the user.
* @param choiceDescription A meaningful, human-readable description of the choice to be made,
* which is most likely in the form of either a direct or indirect
* question.
* @param defaultChoiceId The id of the choice that should be chosen if the decision times out
* before the user has chosen their own choice.
* @return An XML string with the following format:
*
* [timeoutLengthMinutes]
* [choiceDescription]
*
*
*/
private String createStartChoiceMomentXml(String momentId, double timeoutLengthMinutes,
String choiceDescription, String defaultChoiceId) {
String xml = "";
xml += createStartMomentXml("choice", momentId);
xml += "" + Double.toString(timeoutLengthMinutes)
+ "";
xml += "" + choiceDescription + "";
xml += "";
return xml;
}
/**
* A helper function to create an XML string representing a choice. Choices are found within
* choice moments.
* @param choiceId The id of the choice.
* @param choiceDescription A meaningful, human-readable description of the choice.
* @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this
* moment is the last moment in the mission.
* @param depleteWeaponCharge Whether the user's weapon should be depleted if they select this
* choice.
* @param incrementNumEnemiesDefeated Whether the number of enemies defeated should be
* incremented if the user selects this choice.
* @param iconResourceName The name of the drawable resource for this choice action.
* @return An XML string with the following format:
*
* [choiceDescription]
*
*
*
*
*/
private String createChoiceXml(String choiceId, String choiceDescription, String nextMomentId,
boolean depleteWeaponCharge,
boolean incrementNumEnemiesDefeated, String iconResourceName) {
String xml = "";
xml += "";
xml += "" + choiceDescription + "";
xml += createNextMomentXml(nextMomentId);
xml += "";
if (iconResourceName != null) {
xml += createIconXML(iconResourceName);
}
xml += "";
return xml;
}
/**
* A helper function to create an XML string representing the end of a choice moment.
* @return A moment XML end-tag:
*/
private String createEndChoiceMomentXml() {
return createEndMomentXml();
}
/**
* A helper function to create an XML string representing a spoken text moment.
* @param momentId The unique id of this moment.
* @param nextMomentId The id of the next moment in the mission. Can be null if this moment is
* the last moment in the mission.
* @param textToSpeak A string that should be spoken aloud as part of this moment.
* @return An XML string with the following format:
*
*
* [textToSpeak]
*
*/
private String createSpokenTextMomentXml(String momentId, String nextMomentId,
String textToSpeak) {
String xml = "";
xml += createStartMomentXml("spoken_text", momentId);
xml += createNextMomentXml(nextMomentId);
xml += "" + textToSpeak + "";
xml += createEndMomentXml();
return xml;
}
/**
* A helper function to create an XML string representing a sfx moment.
* @param momentId The unique id of this moment.
* @param nextMomentId The id of the next moment in the mission. Can be null if this moment is
* the last moment in the mission.
* @param pathToResource The absolute path to the sound resource to be played as part of this
* moment.
* @return An XML string with the following format:
*
*
* [pathToResource]
*
*/
private String createSfxMomentXml(String momentId, String nextMomentId, String pathToResource) {
String xml = "";
xml += createStartMomentXml("sfx", momentId);
xml += createNextMomentXml(nextMomentId);
xml += "" + pathToResource + "";
xml += createEndMomentXml();
return xml;
}
/**
* A helper function to create an XML string representing a timer moment's 'length_minutes'
* element.
* @param lengthMinutes The length of the timer moment in minutes.
* @return An XML string with the following format:
* [lengthMinutes]
*/
private String createLengthMinutesXml(double lengthMinutes) {
return "" + Double.toString(lengthMinutes) + "";
}
/**
* A helper function to create an XML string representing a 'fictional_progress' element.
* @param progressDescription The fictional progress made.
* @return An XML string with the following format:
* [progressDescription]
*/
private String createFictionalProgressXml(String progressDescription) {
return "" + progressDescription + "";
}
/**
* A helper function to create an XML string representing an 'icon' element.
* @param iconResourceName The name of the drawable resource for this choice action.
* @return An XML string with the following format:
*
*/
private String createIconXML(String iconResourceName) {
return "";
}
/**
* A helper function to create an XML string representing a spoken text moment with fictional
* progress.
* @param momentId The unique id of this moment.
* @param nextMomentId The id of the next moment in the mission. Can be null if this moment is
* the last moment in the mission.
* @param textToSpeak A string that should be spoken aloud as part of this moment.
* @param progressDescription A string describing the fictional progress.
* @return An XML string with the following format:
*
*
* [textToSpeak]
* [progressDescription]
*
*/
private String createSpokenTextMomentWithFictionalProgressXML(String momentId,
String nextMomentId, String textToSpeak, String progressDescription) {
String xml = "";
xml += createStartMomentXml("spoken_text", momentId);
xml += createNextMomentXml(nextMomentId);
xml += "" + textToSpeak + "";
xml += createFictionalProgressXml(progressDescription);
xml += createEndMomentXml();
return xml;
}
/**
* A helper function to create an XML string representing a timer moment with fictional
* progress.
* @param momentId The unique id of the moment.
* @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this
* moment is the last moment in the mission.
* @param lengthMinutes The length of the timer moment in minutes.
* @param progressDescription A string describing the fictional progress.
* @return An XML string of the following format:
*
*
* [lengthMinutes]
* [progressDescription]
*
*/
private String createTimerMomentWithFictionalProgressXML(String momentId, String nextMomentId,
double lengthMinutes, String progressDescription) {
String xml = "";
xml += createStartMomentXml("timer", momentId);
xml += createNextMomentXml(nextMomentId);
xml += createLengthMinutesXml(lengthMinutes);
xml += createFictionalProgressXml(progressDescription);
xml += createEndMomentXml();
return xml;
}
/**
* A helper function to create an XML string representing a sfx moment with fictional progress.
* @param momentId The unique id of this moment.
* @param nextMomentId The id of the next moment in the mission. Can be null if this moment is
* the last moment in the mission.
* @param pathToResource The absolute path to the sound resource to be played as part of this
* moment.
* @param progressDescription A string describing the fictional progress.
* @return An XML string with the following format:
*
*
* [pathToResource]
* [progressDescription]
*
*/
private String createSfxMomentWithFictionalProgressXML(String momentId, String nextMomentId,
String pathToResource, String progressDescription) {
String xml = "";
xml += createStartMomentXml("sfx", momentId);
xml += createNextMomentXml(nextMomentId);
xml += "" + pathToResource + "";
xml += createFictionalProgressXml(progressDescription);
xml += createEndMomentXml();
return xml;
}
/**
* A helper function to create an XML string representing the start of a choice moment with
* fictional progress.
* @param momentId The unique id of the moment.
* @param timeoutLengthMinutes The length of time in minutes after which the default choice
* should be chosen for the user.
* @param choiceDescription A meaningful, human-readable description of the choice to be made,
* which is most likely in the form of either a direct or indirect
* question.
* @param defaultChoiceId The id of the choice that should be chosen if the decision times out
* before the user has chosen their own choice.
* @param progressDescription A string describing the fictional progress.
* @return An XML string with the following format:
*
* [timeoutLengthMinutes]
* [choiceDescription]
*
* [progressDescription]
*/
private String createStartChoiceMomentWithFictionalProgressXML (String momentId,
double timeoutLengthMinutes, String choiceDescription, String defaultChoiceId,
String progressDescription) {
String xml = "";
xml += createStartChoiceMomentXml(momentId, timeoutLengthMinutes, choiceDescription,
defaultChoiceId);
xml += createFictionalProgressXml(progressDescription);
return xml;
}
/**
* A helper function to create an XML string representing a choice. Choices are found within
* choice moments. Contains a piece of fictional progress.
* @param choiceId The id of the choice.
* @param choiceDescription A meaningful, human-readable description of the choice.
* @param nextMomentId The id of the next moment if this choice is chosen. Can be null if this
* moment is the last moment in the mission.
* @param depleteWeaponCharge Whether the user's weapon should be depleted if they select this
* choice.
* @param incrementNumEnemiesDefeated Whether the number of enemies defeated should be
* incremented if the user selects this choice.
* @param iconResourceName The name of the drawable resource for this choice action.
* @return An XML string with the following format:
*
* [choiceDescription]
*
*
* [progressDescription]
*
*
*/
private String createChoiceWithFictionalProgressXML(String choiceId, String choiceDescription,
String nextMomentId, boolean depleteWeaponCharge, boolean incrementNumEnemiesDefeated,
String progressDescription, String iconResourceName) {
String xml = "";
xml += "";
xml += "" + choiceDescription + "";
xml += createNextMomentXml(nextMomentId);
xml += "";
xml += createFictionalProgressXml(progressDescription);
if (iconResourceName != null) {
xml += createIconXML(iconResourceName);
}
xml += "";
return xml;
}
}
================================================
FILE: app/src/main/AndroidManifest.xml
================================================
================================================
FILE: app/src/main/assets/legacy_missions/choice_mission.xml
================================================
0.5What will you do?Fire!!!Use a sling shot.Drop a smoke bomb.0.1
================================================
FILE: app/src/main/assets/legacy_missions/mission.xml
================================================
0.25Created a mission.Made a timer moment0.5Example ChoiceMoment DescriptionExample Choice Description 1Fired a weapon.Example Choice Description 2Example Choice Description 2path/to/somethingHello!
================================================
FILE: app/src/main/assets/legacy_missions/sfx mission.xml
================================================
You will now hear a snap sound.android.resource://com.google.fpl.gim.examplegame/raw/snapThat was a snap! You're welcome.
================================================
FILE: app/src/main/assets/legacy_missions/spoken_plus_timer_mission.xml
================================================
This is the first moment in this mission. The next moment should be a timer moment
lasting 6 seconds.
0.1
This is the final moment, and the previous moment lasted 6 seconds.
================================================
FILE: app/src/main/assets/legacy_missions/texttospeechmission.xml
================================================
Hello!Agent, your mission is simple. Good luck. Godspeed!
================================================
FILE: app/src/main/assets/legacy_missions/timermission.xml
================================================
0.10.10.1
================================================
FILE: app/src/main/assets/missions/01_sample_mission_1.xml
================================================
Welcome to Games In Motion! The year is 2012, and the apocalypse is upon us in the form
of zombies. The zombies have decided that your brain looks particularly tasty, and a
swarm is after you. You will be pursued relentlessly until you reach the base, which is
approximately 3 minutes away by foot. You will be notified when a zombie begins to
chase you, and you will have to react appropriately. Keep an eye on your wrist gadget,
but don't run into any trees, or else the zombies will surely catch you. Good luck!
Start running now! You have at least a minute before a zombie will begin to chase you.
Started a missionReceived instructions3
You are now being chased! Your options are as follows: Number 1. Act like a zombie in
order to blend in. Number 2. Throw an axe at the zombie. Make your choice using your
mobile device. Choose wisely.
Encountered a zombie0.5What will you do?Fire!!!Axe.Threw an axe.Blend.Pretended to be a zombieandroid.resource://com.google.fpl.gim.examplegame/raw/axeandroid.resource://com.google.fpl.gim.examplegame/raw/brains
You defeated the zombie! Good thing because
Killed the zombie!
You were caught! That's okay because
Failed at pretending to be a zombie.
You have arrived at the base.
Arrived at the base.
================================================
FILE: app/src/main/assets/missions/02_sample_mission_2.xml
================================================
Hello Agent. Welcome to Games In Motion! The year is 2012, and the apocalypse is upon
us in the form of zombies. Your task is to make it to our base. But the zombies have
decided that your brain looks particularly tasty, and a swarm is after you. You will be
pursued relentlessly until you reach the base, which is approximately 20 minutes away by
foot. Keep an eye on your wrist gadget: you will be notified when a zombie begins to
chase you, and you will have to react appropriately. Don’t run into any trees, or else
the zombies will surely catch you. We’ve provided you with a simple super charger. Run
faster, and you’ll get a shot to use against the zombies. Good luck! Start running now!
You have at least a minute before a zombie will begin to chase you.
Agent: Apocalypse3.0
Watch out, there is a zombie behind you! Look at your wrist gadget and act quickly to
defeat the them. If you’ve got a shot, you can take it. Otherwise, you can act like a
zombie in order to blend in. Or, throw an axe at the zombie. Choose wisely.
0.5Face the first zombie!Fire!!!Axe.Blend.android.resource://com.google.fpl.gim.examplegame/raw/fireandroid.resource://com.google.fpl.gim.examplegame/raw/axeandroid.resource://com.google.fpl.gim.examplegame/raw/brains
Right in the eye! Nice work, agent. You just might have this zombie thing down.
Hum. I did not expect that to work. Well, keep it up!
Why on earth did you think blending in would work? You barely got out of that! You’ll never be a great agent if you act like that.
3.03.0
All right agent, I have a real task for you now.
How would you like a chance to redeem yourself?
There’s a fork in the road ahead. We have intel suggesting that a zombie mans the split.
One of the paths leads to a bunker, and that bunker has a hard drive we need you to get.
Don’t worry if you can’t find it right away - but know that the zombie may pursue if you
get their attention. If you take care of them quickly, they might have something on
their person. Or is it just a body since they are dead? Undead? Anyway, it will tell you
where to go.
0.5Fork in the roadFire!!!Left - sneakRight - sneakandroid.resource://com.google.fpl.gim.examplegame/raw/fireandroid.resource://com.google.fpl.gim.examplegame/raw/sneak
Well done. And I was right, of course. The zombie had a slip of paper saying to go left.
Head down the path. It will be obvious when you get there.
You certainly have his attention now. How disappointing. And, and, what are you doing?
Do you really think jumping into the bramble will help you here? You're just making
noise. Perhaps if you're extraordinarily lucky, you can lose the zombie on your tail.
Sigh. Now I have to make contingency plans to recover that hard drive, all because of
your stupidity.
3.03.0
Right time, right location. I like your consistency, agent. Much better than the other
candidates we were investigating. You are doing so well that I apologize for the
pedantic explanation of your next task.
I am in shock at your luck. How did you lose that zombie? I swear they were following
you the entire time. And how did you find the bunker after all that? You do realize
that good luck does not a good agent make? But as long as you are here, you might as
well be useful.
Go inside, go downstairs, turn left. 3 doors down will be a room labeled Animatrix.
You'll need to break the window, get in, and grab the blue external hard drive next to
the large computer. You will lose contact in there, but I will check in again once you
get out.
3.0
You got out. By the way, there is a horde of zombies chasing you. Why aren’t you
running now? Didn’t I warn you about them? We saw them on the radar nearly 10 minutes
ago. Oh well. Better late than never I suppose. Start running now!
3.0
You are at the base now, but the horde is still chasing you. The horde is thinner now,
but we can’t let you in until you defeat them. Our own safety is much more important
than yours, after all. Deal with them. Or we will deal with you.
0.5The horde is here.Fire!!!Join them.Jetpack!android.resource://com.google.fpl.gim.examplegame/raw/fireandroid.resource://com.google.fpl.gim.examplegame/raw/brainsandroid.resource://com.google.fpl.gim.examplegame/raw/jetpack
I suppose that firing like a maniac into a horde of zombies is one way to go.
Shockingly, you were successful. I guess that means we have to let you in now.
Darn it. Well, you completed the mission, so you are now an agent. I begrudgingly
offer my congratulations.
You have decided to join them? How rude. Needless to say, you did not complete the
mission, and your agent status has been revoked. We might consider granting it to you
again, but not until you return for your next mission. Farewell.
Where did that jetpack come from? And how inconsiderate of you to leave us behind to
deal with the horde. Needless to say, you did not complete the mission, and your agent
status has been revoked. We might consider granting it to you again, but not until you
return for your next mission. Farewell.
Mission end.
================================================
FILE: app/src/main/assets/missions/ex_01_timer_moment.xml
================================================
0.5Played a mission!Played a timer moment
================================================
FILE: app/src/main/assets/missions/ex_02_spoken_text_moment.xml
================================================
Hello! This is a spoken text moment that uses text to speech.
Heard a spoken text moment
================================================
FILE: app/src/main/assets/missions/ex_03_choice_moment.xml
================================================
0.5What will you do?Made a choiceFire!!!Use a sling shot.Used a slingshotDrop a smoke bomb.Used a smoke bomb
================================================
FILE: app/src/main/assets/missions/ex_04_sfx_moment.xml
================================================
android.resource://com.google.fpl.gim.examplegame/raw/brainsBRAINSBRAINS BRAINS BRAINSBRAAAAAAAAAAAAAAAINS
================================================
FILE: app/src/main/assets/missions/ex_05_broken_timer_moment.xml
================================================
Played a mission!Played a timer moment
================================================
FILE: app/src/main/assets/missions/ex_06_long_timer_mission.xml
================================================
100.0
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/Choice.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import java.util.ArrayList;
/**
* Describes an option that a user has when presented with a decision to make.
* Choices are only meaningful when there are 2+ of them.
*/
public class Choice {
// Unique identifier for this Choice.
private String mChoiceId;
// The description of this option.
private String mDescription;
// The moment to go to next.
private String mNextMomentId;
// The set of changes to make if the player chooses this option.
private Outcome mOutcome;
// Whether or not this Choice requires a charged weapon.
private boolean mRequiresChargedWeapon;
// Fictional Progress associated with this choice.
private ArrayList mFictionalProgress;
// The name of the resource icon to display for this Choice's action.
private String mDrawableResourceName;
public Choice(String choiceId, String text, String nextMomentId, Outcome outcome,
boolean requiresChargedWeapon, ArrayList fictionalProgress,
String drawableResourceName) {
mChoiceId = choiceId;
mDescription = text;
mNextMomentId = nextMomentId;
mOutcome = outcome;
mRequiresChargedWeapon = requiresChargedWeapon;
mFictionalProgress = fictionalProgress;
mDrawableResourceName = drawableResourceName;
}
public String getChoiceId() {
return mChoiceId;
}
public String getDescription() {
return mDescription;
}
public String getNextMomentId() {
return mNextMomentId;
}
public Outcome getOutcome() {
return mOutcome;
}
public ArrayList getFictionalProgress() {
return mFictionalProgress;
}
public boolean requiresChargedWeapon() {
return mRequiresChargedWeapon;
}
public String getDrawableResourceName() {
return mDrawableResourceName;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/ChoiceMoment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.fpl.gim.examplegame.gui.NotificationOptions;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.util.ArrayList;
/**
* Describes a Moment in which the user is presented with a decision to make.
*/
public class ChoiceMoment extends Moment {
private static final String TAG = ChoiceMoment.class.getSimpleName();
public static final int MAXIMUM_NUM_OF_CHOICES = 3;
public static final int MINIMUM_NUM_OF_CHOICES = 2;
private static final String CHOICE_NOTIFICATION_ACTION_1
= "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_1";
private static final String CHOICE_NOTIFICATION_ACTION_2
= "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_2";
private static final String CHOICE_NOTIFICATION_ACTION_3
= "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_3";
private static final String CHOICE_ID_KEY
= "com.google.fpl.gim.examplegame.CHOICE_ID_KEY";
private static final String ICON_RESOURCE_FOLDER = "drawable";
private static long[] VIBRATE_PATTERN = {0, 300, 100, 300, 100, 300};
private ChoiceMomentData mData;
private long mStartTimeNanos;
private Choice mSelectedChoice = null;
public ChoiceMoment (Mission mission, ChoiceMomentData data) {
super(mission);
this.mData = data;
}
public void update(long nowNanos) {
Utils.logDebug(TAG, "ChoiceMoment \"" + mData.getMomentId() + "\" update.");
if (!isDone() && hasTimeToMakeChoiceExpired(nowNanos)) {
// Pick default choice
if (noChoiceSelectedYet()) {
selectChoice(mData.getDefaultChoiceId());
}
setIsDone(true);
}
}
@Override
public void start(long nowNanos) {
super.start(nowNanos);
Utils.logDebug(TAG, "ChoiceMoment \"" + mData.getMomentId() + "\" started.");
setStartTimeNanos(nowNanos);
// If the user's weapon is not charged, the choice to fire their weapon should not be
// displayed.
Choice[] choices = mData.getChoices();
int numActions = mData.getNumChoices();
if (!getMission().isWeaponCharged()) {
numActions--;
}
// Create notification actions using the valid choices.
NotificationCompat.Action[] actions = new NotificationCompat.Action[numActions];
int index = 0;
String[] allActions = {CHOICE_NOTIFICATION_ACTION_1, CHOICE_NOTIFICATION_ACTION_2,
CHOICE_NOTIFICATION_ACTION_3};
for (Choice choice : choices) {
if (!choice.requiresChargedWeapon() || getMission().isWeaponCharged()) {
// Bounds checked in MissionParser.java, which requires each choice moment to have
// 2 or 3 choices associated with it.
Intent actionIntent = new Intent(allActions[index]);
actionIntent.putExtra(CHOICE_ID_KEY, choice.getChoiceId());
String resourceName = choice.getDrawableResourceName();
String packageName = getMission().getService().getPackageName();
int resource = getMission().getService().getResources()
.getIdentifier(resourceName, ICON_RESOURCE_FOLDER, packageName);
// If the resource does not exist, default to using application icon.
if (resource == 0) {
resource = getMission().getService().getApplicationInfo().icon;
}
actions[index] = getMission().getService()
.makeNotificationAction(actionIntent, resource,
choice.getDescription());
index++;
}
}
// Create the notification to warn the user of an approaching enemy.
NotificationOptions notificationOptions =
NotificationOptions.getDefaultNotificationOptions();
notificationOptions.setNotificationId(MainService.CHOICE_NOTIFICATION_ID);
notificationOptions.setPriorityAsMax();
notificationOptions.setActions(actions);
notificationOptions.setNotificationDefaults(0);
notificationOptions.setVibratePattern(VIBRATE_PATTERN);
getMission().getService().postActionNotification(notificationOptions);
}
@Override
public void end() {
Utils.logDebug(TAG, "ChoiceMoment \"" + mData.getMomentId() + "\" ended.");
// Remove choice notification.
dismissNotification();
}
/**
* The next moment is not defined for a ChoiceMoment until the user has selected a choice.
* @return Returns null until a choice is made, then returns the nextMomentId.
*/
@Override
public String getNextMomentId() {
if (mSelectedChoice == null) {
return null;
} else {
return mSelectedChoice.getNextMomentId();
}
}
@Override
public void restart(long nowNanos) {
start(nowNanos);
}
public ChoiceMomentData getMomentData() {
return this.mData;
}
public void setStartTimeNanos(long startTimeNanos) {
this.mStartTimeNanos = startTimeNanos;
}
public boolean hasTimeToMakeChoiceExpired(long nowNanos) {
return (nowNanos - mStartTimeNanos) >= Utils.minutesToNanos(mData
.getTimeoutLengthMinutes());
}
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(CHOICE_NOTIFICATION_ACTION_1)
|| intent.getAction().equals(CHOICE_NOTIFICATION_ACTION_2)
|| intent.getAction().equals(CHOICE_NOTIFICATION_ACTION_3)) {
String choiceId = intent.getStringExtra(CHOICE_ID_KEY);
selectChoice(choiceId);
}
}
public synchronized void selectChoice(String choiceId) {
if (!isDone()) {
Utils.logDebug(TAG, "Choice with id \"" + choiceId + "\" selected.");
mSelectedChoice = mData.getChoiceById(choiceId);
getMission().applyOutcome(mSelectedChoice.getOutcome());
setIsDone(true);
}
}
public void dismissNotification() {
NotificationManager notificationManager = (NotificationManager) getMission().getService()
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(MainService.CHOICE_NOTIFICATION_ID);
}
public boolean noChoiceSelectedYet() {
return mSelectedChoice == null;
}
@Override
public ArrayList getFictionalProgress() {
ArrayList progress = new ArrayList<>();
progress.addAll(mData.getFictionalProgress());
if (!noChoiceSelectedYet()) {
progress.addAll(mSelectedChoice.getFictionalProgress());
}
return progress;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/ChoiceMomentData.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Encapsulates the data that is needed to define a unique ChoiceMoment.
*/
public class ChoiceMomentData extends MomentData {
// The text describing the choice the player must make.
private final String mDescription;
// All of the choices that the user can have.
private final HashMap mChoices;
// Identifies the default Choice to execute in the case of a timeout.
private final String mDefaultChoiceId;
// Time in minutes until the default Choice is executed.
private final float mTimeoutLengthMinutes;
/**
* Constructor to explicitly set all fields for a ChoiceMomentData.
* @param momentId Identifier for the ChoiceMoment.
* @param fictionalProgress Fictional progress for this moment.
* @param description Text description for the decision to be made.
* @param choices HashMap of Choices available to choose.
* @param defaultChoiceId Default Choice in case of timeout.
* @param timeoutLengthMinutes Length of time until timeout.
*/
public ChoiceMomentData(String momentId, ArrayList fictionalProgress,
String description, HashMap choices, String defaultChoiceId,
float timeoutLengthMinutes) {
super(momentId, null, fictionalProgress);
mDescription = description;
mChoices = choices;
mDefaultChoiceId = defaultChoiceId;
mTimeoutLengthMinutes = timeoutLengthMinutes;
}
/**
* Constructor for information from XML.
* @param momentId Identifier for the ChoiceMoment.
* @param fictionalProgress Fictional progress for this moment.
* @param description Text description for the decision to be made.
* @param defaultChoiceId Default Choice in case of timeout.
* @param timeoutLengthMinutes Length of time until timeout.
*/
public ChoiceMomentData(String momentId, ArrayList fictionalProgress,
String description, String defaultChoiceId, float timeoutLengthMinutes) {
this(momentId, fictionalProgress, description, new HashMap(),
defaultChoiceId, timeoutLengthMinutes);
}
public String getText() {
return mDescription;
}
public Choice[] getChoices() {
return mChoices.values().toArray(new Choice[mChoices.size()]);
}
public Choice getChoiceById(String choiceId) {
return mChoices.get(choiceId);
}
public int getNumChoices() {
return mChoices.size();
}
public void addChoice(Choice choice) {
mChoices.put(choice.getChoiceId(), choice);
}
public String getDefaultChoiceId() {
return mDefaultChoiceId;
}
public float getTimeoutLengthMinutes() {
return mTimeoutLengthMinutes;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/MainActivity.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.google.fpl.gim.examplegame.gui.FitnessDataDisplayFragment;
import com.google.fpl.gim.examplegame.gui.GameViews;
import com.google.fpl.gim.examplegame.gui.NotificationOptions;
import com.google.fpl.gim.examplegame.google.GoogleApiClientWrapper;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.util.ArrayList;
/**
* MainActivity class on the UI thread. It has a game handler for the game loop to execute on.
*/
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// Defines the action the BroadcastReceiver will receive.
public static final String ENABLE_BACK
= "com.google.fpl.gim.examplegame.ENABLE_BACK";
public static final String MISSION_START
= "com.google.fpl.gim.examplegame.MISSION_START";
public static final String MISSION_END
= "com.google.fpl.gim.examplegame.MISSION_END";
private static final String UPDATE_FITNESS_STATS
= "com.google.fpl.gim.examplegame.UPDATE_FITNESS_STATS";
private MainService mMainService; // Service that runs the game logic.
private GameViews mGameViews; // Container for all UI fragments.
// Defines behavior when binding and unbinding mMainService.
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder binder) {
if (binder == null) {
throw new IllegalArgumentException("IBinder passed to onServiceConnected was null");
}
mMainService = ((MainService.MainBinder) binder).getService();
mMainService.ConnectGoogleFitApiClient(MainActivity.this);
// Register Intent receivers after the service is bound; this ensures that the Activity
// is listening to intents sent from the service.
// Register the mReceiver with an intent filter for rendering requests.
IntentFilter filter = new IntentFilter();
filter.addAction(ENABLE_BACK);
filter.addAction(MISSION_START);
filter.addAction(MISSION_END);
registerReceiver(mReceiver, filter);
// Render the mReceiver with an intent filter for displaying an updated num steps
filter = new IntentFilter();
filter.addAction(UPDATE_FITNESS_STATS);
registerReceiver(mReceiver, filter);
}
public void onServiceDisconnected(ComponentName className) {
mMainService = null;
}
};
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Update the step display fragment to show the current number of steps that the user
// has taken.
if (intent.getAction().equals(UPDATE_FITNESS_STATS)) {
if (mMainService != null) {
FitnessDataDisplayFragment fitnessDataDisplayFragment
= mGameViews.getFitnessDataDisplayFragment();
if (fitnessDataDisplayFragment.isVisible()) {
fitnessDataDisplayFragment.setFitnessStats(
mMainService.getCurrentMission());
}
}
}
// Receives an intent that requests back button to be enabled.
if (intent.getAction().equals(ENABLE_BACK)) {
getFragmentManager().popBackStack();
}
// Receives an intent that requests end summary screen to display due to a mission end.
if (intent.getAction().equals(MISSION_START)) {
displayFitnessStats();
}
// Receives an intent that requests end summary screen to display due to a mission end.
if (intent.getAction().equals(MISSION_END)) {
checkDisplayEndScreen();
}
}
};
@Override
public void onDestroy() {
Utils.logDebug(TAG, "onDestroy");
super.onDestroy();
if (isFinishing()) {
// Stop the service from running in the background if the app exits.
Intent intent = new Intent(this, MainService.class);
intent.setPackage(getPackageName());
stopService(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
getFragmentManager().popBackStack();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GoogleApiClientWrapper.REQUEST_CODE_OAUTH) {
if (resultCode == RESULT_OK) {
// If the user authenticated, try to connect again
mMainService.userAuthenticated();
mMainService.reconnectGoogleApi();
} else {
// Ideally there's a fail case here, handled by our own UX flow.
// Keeping it empty for the sample.
}
}
}
/**
* Responsible for transitioning from the start menu UI to the mission selection menu UI
* @param view The view that is invoking this method.
*/
public void onStartButtonPressed(View view) {
mGameViews.getStartMenuFragment().onStartButtonPressed();
}
public void onEnterPressed(View view) {
mGameViews.getRunSpecificationsFragment().onEnterPressed();
}
public void onStartMissionPressed(View view) {
// Get user selected run and mission information.
String missionName = getGameViews().getListOfMissionsFragment().getSelectedMissionName();
String assetPath = getGameViews().getListOfMissionsFragment().getSelectedAssetPath();
float missionLengthMinutes =
getGameViews().getRunSpecificationsFragment().getSelectedMissionLengthMinutes();
float intervalLengthMinutes =
getGameViews().getRunSpecificationsFragment().getSelectedIntervalLengthMinutes();
float challengePaceMinutesPerMile =
getGameViews().getRunSpecificationsFragment().getSelectedChallengePaceMinutesPerMile();
loadAndStartMission(assetPath, missionName, missionLengthMinutes, intervalLengthMinutes,
challengePaceMinutesPerMile);
// Disable the button and show that we are registering sensors.
getGameViews().getMusicSelectionFragment().disableReadyButton();
}
private void displayFitnessStats() {
String missionName = getGameViews().getListOfMissionsFragment().getSelectedMissionName();
Fragment stepDisplayFragment = getGameViews().getFitnessDataDisplayFragment();
((FitnessDataDisplayFragment)stepDisplayFragment).setMissionName(missionName);
Fragment musicSelectionFragment = getGameViews().getMusicSelectionFragment();
getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.remove(musicSelectionFragment)
.add(R.id.container, stepDisplayFragment, GameViews.FITNESS_DATA_DISPLAY_TAG)
.addToBackStack(null)
.commit();
getFragmentManager().executePendingTransactions();
// Disable home/back button on action bar.
displayHomeUp(false);
}
public GameViews getGameViews() {
return this.mGameViews;
}
public void loadAndStartMission(String missionFilePath, String missionName, float missionLength,
float intervalLength, float challengePaceMinutesPerMile) {
if (mMainService != null) {
mMainService.loadAndStartMission(missionFilePath, missionName, missionLength,
intervalLength, challengePaceMinutesPerMile);
}
}
public void displayHomeUp(boolean display) {
getSupportActionBar().setDisplayHomeAsUpEnabled(display);
getSupportActionBar().setHomeButtonEnabled(display);
}
/**
* Updates UI as Google Fit's connection status changes.
*/
public void onFitStatusUpdated(boolean connected) {
// Hint to the fragments that might need to update their displays.
mGameViews.getStartMenuFragment().onFitStatusUpdated(connected);
mGameViews.getEndSummaryFragment().onFitStatusUpdated(connected);
// End a mission or pop user back to start menu if we are disconnected.
if (!connected) {
if (mMainService != null && mMainService.isMissionRunning()) {
// If a mission is running, end it. No different than a mission ending on its own.
mMainService.endMission();
} else {
// Jump back to the start screen.
getFragmentManager().popBackStack(GameViews.START_MENU_TAG, 0);
}
if (mMainService != null) {
// Post a notification.
NotificationOptions notificationOptions =
NotificationOptions.getDefaultNotificationOptions();
notificationOptions.setTitle(getResources().getString(
R.string.disconnection_notification_title));
notificationOptions.setContent(getResources().getString(
R.string.disconnection_notification_content));
notificationOptions.setNotificationId(MainService.FITNESS_DISCONNECT_NOTIFICATION_ID);
notificationOptions.setPriorityAsHigh();
notificationOptions.setNotificationDefaults(NotificationCompat.DEFAULT_LIGHTS);
mMainService.postActionNotification(notificationOptions);
}
}
}
@Override
public void onBackPressed() {
if (mMainService != null) {
if (!mMainService.isMissionRunning() && canPressBackButton()) {
// If not in a mission and not at the start, function like the in-app up button.
getFragmentManager().popBackStack();
} else if (mMainService.isMissionRunning()) {
// If a mission is running, end it. No different than a mission ending on its own.
mMainService.endMission();
} else {
// Will call finish() and end MainActivity.
super.onBackPressed();
}
}
}
public void setActionBarTitle(int string_res_id) {
getSupportActionBar().setTitle(string_res_id);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
@Override
protected void onStart() {
Utils.logDebug(TAG, "onStart");
super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Utils.logDebug(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start service so it can run in bound and unbound state.
Intent intent = new Intent(this, MainService.class);
intent.setPackage(getPackageName());
startService(intent);
// create new fragments and initialize data
if (savedInstanceState == null) {
mGameViews = new GameViews();
mGameViews.initializeFragments(this);
} else {
// restore old fragments and data
mGameViews.restoreFragments(this);
}
displayHomeUp(canPressBackButton());
getFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
displayHomeUp(canPressBackButton());
}
});
}
@Override
protected void onPause() {
Utils.logDebug(TAG, "onPause");
super.onPause();
// Unregister all broadcasts before unbinding service. These will be registered again once
// the onServiceConnected callback is called. This cannot be unregistered in the
// onServiceConnected callback as MainActivity might be paused at that point, and it will
// result in a crash.
try {
unregisterReceiver(mReceiver);
} catch (IllegalArgumentException e) {
Utils.logDebug(TAG, "Unable to unregister the Broadcast Receiver.");
}
// Unbind to allow service to run in the background.
unbindService(mConnection);
}
@Override
protected void onResume() {
Utils.logDebug(TAG, "onResume");
super.onResume();
// Bind to the already running MainService so we can communicate with it.
Intent intent = new Intent(this, MainService.class);
intent.setPackage(getPackageName());
bindService(intent, mConnection, Context.BIND_WAIVE_PRIORITY);
// Handles screen being asleep during run. Will display end screen if the run is over.
checkDisplayEndScreen();
}
@Override
protected void onStop() {
Utils.logDebug(TAG, "onStop");
super.onStop();
}
/**
* The back button should be active as long as there are fragment transactions in the back
* stack. We always want the first fragment to be around so the back stack count needs to be
* > 1.
* @return Whether the back button should be active.
*/
private boolean canPressBackButton() {
return getFragmentManager().getBackStackEntryCount() > 1;
}
private void checkDisplayEndScreen() {
if (mMainService != null) {
if (mMainService.shouldDisplayEndScreen()) {
displayEndScreen();
}
}
}
/**
* Displays end run summary, with fictional and fitness results.
*/
private void displayEndScreen() {
getFragmentManager().popBackStack(GameViews.START_MENU_TAG, 0);
getFragmentManager().beginTransaction()
.replace(R.id.container, mGameViews.getEndSummaryFragment(),
GameViews.END_SUMMARY_TAG)
.addToBackStack(null)
.commit();
getFragmentManager().executePendingTransactions();
// Get results.
ArrayList fictionalProgress = new ArrayList<>();
ArrayList fitnessResults = new ArrayList<>();
if (mMainService != null) {
fictionalProgress.addAll(mMainService.getOverallFictionalProgress());
fitnessResults.addAll(mMainService.getFitnessStatistics());
}
// Display results.
mGameViews.getEndSummaryFragment().displayStats(fictionalProgress, fitnessResults);
// Unlock first mission achievement
if(mMainService.unlockAchievement(getString(R.string.ach_id_first_mission))) {
Utils.logDebug(TAG, "Achievement Unlocked: First Mission");
} else {
Utils.logDebug(TAG, "Warning: could not unlock achievement, not connected");
}
if (mMainService != null) {
mMainService.reset();
}
displayHomeUp(true);
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/MainService.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.widget.Toast;
import com.google.android.gms.games.Games;
import com.google.fpl.gim.examplegame.gui.GameViews;
import com.google.fpl.gim.examplegame.gui.NotificationOptions;
import com.google.fpl.gim.examplegame.google.GoogleApiClientWrapper;
import com.google.fpl.gim.examplegame.utils.MissionParseException;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Queue;
/**
* This is a Runnable for executing on the UI thread, and will add itself back
* to the UI thread handler at the end of the run() function.
*
* While it will block the UI thread while running, it shouldn't block for that long.
* We could always make a game thread if needed.
*/
public class MainService extends Service implements Runnable, MediaPlayer.OnCompletionListener {
private final IBinder mBinder = new MainBinder();
private static final String TAG = MainService.class.getSimpleName();
private static final String CHOICE_NOTIFICATION_ACTION_1
= "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_1";
private static final String CHOICE_NOTIFICATION_ACTION_2
= "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_2";
private static final String CHOICE_NOTIFICATION_ACTION_3
= "com.google.fpl.gim.examplegame.CHOICE_NOTIFICATION_ACTION_3";
// Ids for notifications.
public static final int CHOICE_NOTIFICATION_ID = 1;
public static final int FITNESS_STATS_NOTIFICATION_ID = 2;
public static final int FITNESS_DISCONNECT_NOTIFICATION_ID = 3;
private static final Locale DEFAULT_TEXT_TO_SPEECH_LOCALE = Locale.UK;
private Mission mMission; // The mission being played. Has reference to current game state.
private static final long DELAY_MILLIS = 1000; // Time between updates, used as Handler delay.
private Handler mUpdateHandler = new Handler();
// Audio related modules.
private TextToSpeech mTextToSpeech;
private boolean mIsTextToSpeechReady = false;
private AudioManager mAudioManager;
private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener;
private MediaPlayer mMediaPlayer;
// A queue of Audio Uris to be played.
private class AudioQueueItem{
Uri mUri;
MediaPlayer.OnCompletionListener mListener;
AudioQueueItem(Uri uri, MediaPlayer.OnCompletionListener listener) {
mUri = uri;
mListener = listener;
}
@Override
public boolean equals(Object o) {
if (getClass() != o.getClass())
return false;
AudioQueueItem audioQueueItem = (AudioQueueItem) o;
return (mUri.equals(audioQueueItem.mUri));
}
}
private Queue mAudioQueue = new LinkedList<>();
private enum State {
UNINITIALIZED,
MISSION_LOADED,
MISSION_RUNNING,
END_SCREEN
}
private State mState = State.UNINITIALIZED;
private GoogleApiClientWrapper mGoogleApiClientWrapper =
new GoogleApiClientWrapper(); // Container for the GoogleApiClient
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (mMission != null && mMission.getMissionData().getCurrentMoment() != null) {
// Choice moment handles choice selection.
((ChoiceMoment) mMission.getMissionData().getCurrentMoment())
.onReceive(context, intent);
}
}
};
/**
* This is the main game loop. Whenever it is done, it adds itself back to the handler.
*/
@Override
public void run() {
if (mState == State.MISSION_LOADED || mState == State.MISSION_RUNNING) {
// This is where we can call the game state and the game logic.
update();
}
mUpdateHandler.postDelayed(this, DELAY_MILLIS);
}
public void userAuthenticated() {
mGoogleApiClientWrapper.userAuthenticated();
}
public void reconnectGoogleApi() {
Utils.logDebug(TAG, "Reconnecting to Google API.");
mGoogleApiClientWrapper.connect();
}
public void ConnectGoogleFitApiClient(Activity activity) {
mGoogleApiClientWrapper.buildGoogleApiClient(activity);
mGoogleApiClientWrapper.connect();
}
/**
* Unlock a Play Games achievement.
*
* @param achievementId the ID of the achievement from the Google Play Developer Console,
* @return true if Achievement unlocked, false otherwise.
*/
public boolean unlockAchievement(String achievementId) {
if (mGoogleApiClientWrapper.isSignedIn()) {
Games.Achievements.unlock(mGoogleApiClientWrapper.getGoogleApiClient(), achievementId);
return true;
} else {
return false;
}
}
/**
* Loads and begins a mission.
*/
public void loadAndStartMission(String missionFilePath, String missionName,
float missionLengthMinutes, float intervalLengthMinutes,
float challengePaceMinutesPerMile) {
if (!canEnterState(State.MISSION_LOADED)) {
return;
}
MissionData data = new MissionData(missionName, missionFilePath, missionLengthMinutes,
intervalLengthMinutes, challengePaceMinutesPerMile);
mMission = new Mission(data);
mMission.setService(this);
// Open an InputStream from the given missionFileName.
InputStream missionStream;
try {
missionStream = getAssets().open(missionFilePath);
} catch (IOException e) {
e.printStackTrace();
requestReselection();
return;
}
// Load the Moments.
try {
mMission.readMoments(missionStream);
} catch (MissionParseException e) {
e.printStackTrace();
requestReselection();
return;
}
try {
missionStream.close();
} catch (IOException e) {
e.printStackTrace();
}
startMission();
}
/**
* Starts a mission.
*/
private void startMission() {
setAndInitNextState(State.MISSION_LOADED);
}
/**
* Ends a mission by halting updates.
*/
public void endMission() {
setAndInitNextState(State.END_SCREEN);
}
@Override
public void onCreate() {
// The service is being created.
Utils.logDebug(TAG, "onCreate");
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_1);
intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_2);
intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_3);
registerReceiver(mReceiver, intentFilter);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Determines the behavior for handling Audio Focus surrender.
mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
|| focusChange == AudioManager.AUDIOFOCUS_LOSS) {
if (mTextToSpeech.isSpeaking()) {
mTextToSpeech.setOnUtteranceProgressListener(null);
mTextToSpeech.stop();
}
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
// Abandon Audio Focus, if it's requested elsewhere.
mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
// Restart the current moment if AudioFocus was lost. Since AudioFocus is only
// requested away from this application if this application was using it,
// only Moments that play sound will restart in this way.
if (mMission != null) {
mMission.restartMoment();
}
}
}
};
// Asynchronously prepares the TextToSpeech.
mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
// Check if language is available.
switch (mTextToSpeech.isLanguageAvailable(DEFAULT_TEXT_TO_SPEECH_LOCALE)) {
case TextToSpeech.LANG_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
Utils.logDebug(TAG, "TTS locale supported.");
mTextToSpeech.setLanguage(DEFAULT_TEXT_TO_SPEECH_LOCALE);
mIsTextToSpeechReady = true;
break;
case TextToSpeech.LANG_MISSING_DATA:
Utils.logDebug(TAG, "TTS missing data, ask for install.");
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
break;
default:
Utils.logDebug(TAG, "TTS local not supported.");
break;
}
}
}
});
mMediaPlayer = new MediaPlayer();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
Utils.logDebug(TAG, "onStartCommand");
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
Utils.logDebug(TAG, "onBind");
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
Utils.logDebug(TAG, "onUnbind");
return true;
}
@Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
Utils.logDebug(TAG, "onRebind");
if (mMission != null) {
mMission.onRebind();
}
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed.
Utils.logDebug(TAG, "onDestroy");
mGoogleApiClientWrapper.disconnect();
if (mIsTextToSpeechReady) {
mTextToSpeech.shutdown();
}
if (mMediaPlayer != null) {
mMediaPlayer.reset();
}
mUpdateHandler.removeCallbacks(this);
unregisterReceiver(mReceiver);
if (mMission != null) {
mMission.cleanup();
}
}
/**
* Callback listener for MediaPlayer.
* @param player MediaPlayer instance.
*/
@Override
public void onCompletion(MediaPlayer player) {
endPlayback();
}
/**
* A Binder for the connection between MainService and MainActivity that allows MainActivity
* to get the running instance of MainService.
*/
public class MainBinder extends Binder {
MainService getService() {
return MainService.this;
}
}
/**
* Create a notification action that upon selection triggers the provided action.
* @param intent Intent to carry out when the notification action is selected.
* @param actionIconResourceId Resource Id of icon for this action.
* @param actionDescription Name of this action.
* @return A notification action that can be selected.
*/
public NotificationCompat.Action makeNotificationAction(Intent intent,
int actionIconResourceId, String actionDescription) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
return new NotificationCompat.Action(actionIconResourceId,
actionDescription, pendingIntent);
}
/**
* Builds and posts a notification from a set of options.
* @param options The options to build the notification.
*/
public void postActionNotification(NotificationOptions options) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(options.getSmallIconResourceId());
builder.setContentTitle(options.getTitle());
builder.setContentText(options.getContent());
builder.setDefaults(options.getNotificationDefaults());
builder.setPriority(options.getNotificationPriority());
builder.setVibrate(options.getVibratePattern());
if (options.getActions() != null) {
for (NotificationCompat.Action action : options.getActions()) {
builder.addAction(action);
}
}
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(options.getNotificationId(), builder.build());
}
public boolean isMissionRunning() {
return mState == State.MISSION_RUNNING;
}
public boolean shouldDisplayEndScreen() {
return mState == State.END_SCREEN;
}
public void reset() {
setAndInitNextState(State.UNINITIALIZED);
}
public ArrayList getOverallFictionalProgress() {
return mMission.getOverallFictionalProgress();
}
/**
* Gets fitness statistics for the last played game.
* @return An array list of fitness statistics to display.
*/
public ArrayList getFitnessStatistics() {
return getCurrentMission().getFitnessStatistics();
}
public Mission getCurrentMission() {
return this.mMission;
}
/**
* Queue a sound into the audio queue.
* @param uri The Uri of the sound.
* @param listener The listener to the sound. This is usually MainService but can be overridden.
*/
public void queueSound(Uri uri, MediaPlayer.OnCompletionListener listener) {
mAudioQueue.offer(new AudioQueueItem(uri, listener));
}
/**
* Removes the first instance of a sound from the audio queue.
* @param uri Uri of the item to be removed.
*/
public void dequeueSound(Uri uri) {
mAudioQueue.remove(new AudioQueueItem(uri, null));
}
/**
* Obtain audio focus for the application. This also checks if we are currently playing any
* other audio clips, so it checks for "audio focus" within the app.
* @return True if audio focus is obtained. False otherwise.
*/
public boolean obtainAudioFocus() {
if (mMediaPlayer.isPlaying() || mTextToSpeech.isSpeaking()) {
return false;
}
int result = mAudioManager.requestAudioFocus(
mAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
return (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED);
}
/**
* End audio playback, and abandon audio focus.
*/
public void endPlayback() {
mMediaPlayer.reset();
mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);
}
protected TextToSpeech getTextToSpeech() { return mIsTextToSpeechReady? mTextToSpeech : null; }
/**
* Checks if the state transition is valid.
* @param state State to transition to.
* @return True if the transition is valid, false if not.
*/
private boolean canEnterState(State state) {
if (mState == state) {
return false;
}
boolean canEnterState = true;
switch (state) {
case UNINITIALIZED:
break;
case MISSION_LOADED:
if (mState == State.MISSION_RUNNING) {
canEnterState = false;
Utils.logDebug(TAG,
"Can not enter MISSION_LOADED state from MISSION_RUNNING state.");
}
break;
case MISSION_RUNNING:
if (mState != State.MISSION_LOADED) {
canEnterState = false;
Utils.logDebug(TAG,
"Can only enter MISSION_RUNNING state from MISSION_LOADED state.");
}
break;
case END_SCREEN:
if (mState != State.MISSION_RUNNING) {
canEnterState = false;
Utils.logDebug(TAG,
"Can only enter END_SCREEN state from MISSION_RUNNING state.");
}
break;
}
return canEnterState;
}
/**
* Sets the next state if possible.
* @param state State to transition to.
*/
private void setAndInitNextState(State state) {
if (!canEnterState(state)) {
return;
}
mState = state;
switch (mState) {
case UNINITIALIZED:
break;
case MISSION_LOADED:
mMission.prepare(mGoogleApiClientWrapper);
mUpdateHandler.post(this);
break;
case MISSION_RUNNING:
mMission.start();
broadcastStart();
break;
case END_SCREEN:
mUpdateHandler.removeCallbacks(this);
mMission.cleanup();
broadcastEnd();
break;
}
}
private void update() {
if (mState == State.MISSION_LOADED && isReady()) {
setAndInitNextState(State.MISSION_RUNNING);
}
if (mState == State.MISSION_RUNNING) {
mMission.update();
if (mMission.isDone()) {
endMission();
}
}
// Consume the audio queue if it's not empty and if we are able to obtain audio focus.
if (!mAudioQueue.isEmpty() && obtainAudioFocus()) {
playFirstInQueue();
}
}
/**
* Play the first item in the audio queue.
*/
private void playFirstInQueue() {
AudioQueueItem queueItem = mAudioQueue.poll();
try {
mMediaPlayer.setDataSource(this, queueItem.mUri);
} catch (IOException e) {
e.printStackTrace();
// Data source does not exist. Skip playback.
endPlayback();
return;
}
mMediaPlayer.setOnCompletionListener(queueItem.mListener);
try {
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
// Error in reading the data source. Skip playback.
endPlayback();
return;
}
mMediaPlayer.start();
}
/**
* @return True if asynchronous preparations are all done, so that a mission can be started.
*/
private boolean isReady() {
return mIsTextToSpeechReady && mGoogleApiClientWrapper.isClientReady();
}
/**
* Broadcast to MainActivity to enable back navigation.
*/
private void enableBackNavigation() {
sendBroadcast(new Intent(MainActivity.ENABLE_BACK));
}
/**
* Display a Toast that requests user to reselect their mission.
*/
private void requestReselection() {
Toast.makeText(this, "Mission load failure. Select again.", Toast.LENGTH_SHORT).show();
enableBackNavigation();
}
/**
* Broadcast to MainActivity that mission has started.
*/
private void broadcastStart() {
sendBroadcast(new Intent(MainActivity.MISSION_START));
}
/**
* Broadcast to MainActivity that mission has ended.
*/
private void broadcastEnd() {
sendBroadcast(new Intent(MainActivity.MISSION_END));
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/Mission.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.data.Value;
import com.google.android.gms.fitness.request.OnDataPointListener;
import com.google.android.gms.fitness.request.SensorRequest;
import com.google.fpl.gim.examplegame.gui.NotificationOptions;
import com.google.fpl.gim.examplegame.google.FitDataTypeSetting;
import com.google.fpl.gim.examplegame.google.GoogleApiClientWrapper;
import com.google.fpl.gim.examplegame.utils.MissionParseException;
import com.google.fpl.gim.examplegame.utils.MissionParser;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.io.InputStream;
import java.util.ArrayList;
/**
* A mission is a complete gameplay during which the exercising user will be challenged to defeat
* fictional pursuers. The user will have a weapon that can only be charged by running faster.
*/
public class Mission implements OnDataPointListener {
private static final String TAG = Mission.class.getSimpleName();
private static final FitDataTypeSetting[] TRACKED_DATA_TYPES = {
new FitDataTypeSetting(
true /* isRequired */, DataType.TYPE_STEP_COUNT_DELTA, 1 /* samplingRateSeconds */,
SensorRequest.ACCURACY_MODE_DEFAULT),
new FitDataTypeSetting(
false /* isRequired */, DataType.TYPE_SPEED, 1 /* samplingRateSeconds */,
SensorRequest.ACCURACY_MODE_HIGH),
};
private static final String UPDATE_FITNESS_STATS
= "com.google.fpl.gim.examplegame.UPDATE_FITNESS_STATS";
// ID that signifies the moment whose next is this is an ending moment.
private static final String DEFAULT_END_ID = null;
private MissionData mData;
// Access to MainService to obtain and use Android Context.
private MainService mService;
private boolean mIsDone = false;
private boolean mIsStarted = false;
// Access to GoogleFitApiClient for fit data
private GoogleApiClientWrapper mGoogleApiClientWrapper;
// Fitness stats for the mission as a whole.
private int mTotalNumStepsTaken = 0;
private int mTotalNumIntervalsCompleted = 0;
private long mMissionStartTimeNanos;
// Fitness stats for a small portion of the mission.
private int mNumStepsSinceBeginningOfSample = 0;
private long mSampleStartTimeNanos;
private float mCurrentAverageMinutesPerMile = 0f;
private static final float AVERAGE_SPEED_SAMPLE_RATE_SECONDS = 10.0f;
private static final float LENGTH_OF_RUNNING_STRIDE_FEET = 5.5f;
private static final float MAXIMUM_MINUTES_PER_MILE = 1000f;
private boolean mIsAtChallengePace = false;
private long mTimestampStartOfChallengePaceNanos;
private static final String AT_CHALLENGE_PACE_RESOURCE
= "android.resource://com.google.fpl.gim.examplegame/raw/atchallengepace";
private static final String NO_LONGER_AT_CHALLENGE_PACE_RESOURCE
= "android.resource://com.google.fpl.gim.examplegame/raw/nolongeratchallengepace";
private static final String WEAPON_CHARGED_RESOURCE
= "android.resource://com.google.fpl.gim.examplegame/raw/weaponcharged";
private final Uri AT_CHALLENGE_PACE_URI = Uri.parse(AT_CHALLENGE_PACE_RESOURCE);
private final Uri NO_LONGER_AT_CHALLENGE_PACE_URI =
Uri.parse(NO_LONGER_AT_CHALLENGE_PACE_RESOURCE);
private final Uri WEAPON_CHARGED_URI = Uri.parse(WEAPON_CHARGED_RESOURCE);
// The current time represented in nanoseconds.
private long mNowNanos;
private boolean mIsWeaponCharged = false;
private float mLastWeaponCharge;
private int mNumEnemiesDefeated = 0;
private ArrayList mOverallFictionalProgress = new ArrayList<>();
public Mission(MissionData data) {
this.mData = data;
}
/**
* Makes the moment referred to by nextMomentId the current Moment. Checks if the game should
* end by checking the nextMomentId.
* @param nextMomentId The ID of the moment to make the current moment.
*/
public void changeCurrentMoment(String nextMomentId, long now) {
if (nextMomentId == DEFAULT_END_ID || nextMomentId.equals(DEFAULT_END_ID)) {
mIsDone = true;
return;
}
mData.setCurrentMomentId(nextMomentId);
mData.getCurrentMoment().start(now);
}
/**
* Loads the moments read from an xml file that define a mission into the mission data.
* @param missionStream An input stream for an xml file.
* @throws com.google.fpl.gim.examplegame.utils.MissionParseException Thrown when file parsing failed due to parser configuration,
* input exceptions, or incorrectly structured file.
*/
public void readMoments(InputStream missionStream) throws MissionParseException {
// Exceptions may be thrown from MissionParser.parseMission
MissionParser.parseMission(missionStream, this);
}
public void start() {
mNowNanos = System.nanoTime();
mMissionStartTimeNanos = mNowNanos;
changeCurrentMoment(mData.getFirstMomentId(), mNowNanos);
mIsStarted = true;
mSampleStartTimeNanos = mNowNanos;
mLastWeaponCharge = 0f;
// Create the notification to notify the user of their current fitness statistics.
postFitnessNotification(getFitnessNotificationTitle());
}
public void cleanup() {
Utils.logDebug(TAG, mOverallFictionalProgress.toString());
// Clean up the current moment.
if (mData.getCurrentMoment() != null) {
mData.getCurrentMoment().end();
}
NotificationManager notificationManager = (NotificationManager) getService()
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(MainService.CHOICE_NOTIFICATION_ID);
notificationManager.cancel(MainService.FITNESS_STATS_NOTIFICATION_ID);
if (mGoogleApiClientWrapper != null) {
mGoogleApiClientWrapper.endFitDataSession(TRACKED_DATA_TYPES, this);
mGoogleApiClientWrapper = null;
}
}
public void addMoment(String id, Moment moment) {
this.mData.addMoment(id, moment);
}
public void setFirstMomentId(String firstMomentId) {
this.mData.setFirstMomentId(firstMomentId);
}
public void update() {
mNowNanos = System.nanoTime();
// Calculate average speed at a consistent time interval.
float timePassedSeconds = Utils.nanosToSeconds(mNowNanos - mSampleStartTimeNanos);
if (timePassedSeconds >= AVERAGE_SPEED_SAMPLE_RATE_SECONDS) {
calculateAverageMinutesPerMile();
}
Moment currentMoment = mData.getCurrentMoment();
currentMoment.update(mNowNanos);
if (currentMoment.isDone()) {
mOverallFictionalProgress.addAll(currentMoment.getFictionalProgress());
currentMoment.end();
changeCurrentMoment(currentMoment.getNextMomentId(), mNowNanos);
}
if (mLastWeaponCharge != getWeaponChargedPercentage()) {
mLastWeaponCharge = getWeaponChargedPercentage();
// Create the notification to notify the user of their current fitness statistics.
postFitnessNotification(getFitnessNotificationTitle());
}
Intent updateFitnessStatsIntent = new Intent();
updateFitnessStatsIntent.setAction(UPDATE_FITNESS_STATS);
getService().sendBroadcast(updateFitnessStatsIntent);
}
public void postFitnessNotification(String title) {
NotificationOptions notificationOptions =
NotificationOptions.getDefaultNotificationOptions();
notificationOptions.setTitle(title);
notificationOptions.setContent(getService()
.getString(R.string.weapon_status_notification_text));
notificationOptions.setNotificationId(MainService.FITNESS_STATS_NOTIFICATION_ID);
notificationOptions.setPriorityAsHigh();
notificationOptions.setNotificationDefaults(NotificationCompat.DEFAULT_LIGHTS);
getService().postActionNotification(notificationOptions);
}
public void setService(MainService service) {
this.mService = service;
}
public MainService getService() {
return this.mService;
}
public boolean isDone() {
return mIsDone;
}
public void prepare(GoogleApiClientWrapper googleApiClientWrapper) {
Utils.logDebug(TAG, "Mission prepared.");
// Start collecting Google Fit data
mGoogleApiClientWrapper = googleApiClientWrapper;
mGoogleApiClientWrapper.startFitDataSession(
TRACKED_DATA_TYPES, getMissionData().getMissionName(), this);
}
public boolean isWeaponCharged() {
return mIsWeaponCharged;
}
public MissionData getMissionData() {
return this.mData;
}
/**
* Restarts the current moment with a time delay.
*/
public void restartMoment() {
if (mData.getCurrentMoment() != null) {
mData.getCurrentMoment().restartWithDelay(mNowNanos, 0f);
}
}
public void applyOutcome(Outcome outcome) {
if (outcome.numEnemiesDefeatedIncremented()) {
mNumEnemiesDefeated++;
}
if (outcome.weaponChargeDepleted()) {
mIsWeaponCharged = false;
}
}
public ArrayList getOverallFictionalProgress() {
return mOverallFictionalProgress;
}
@Override
public void onDataPoint(DataPoint dataPoint) {
// If we get data before the mission has started, discard them.
if (!mIsStarted) {
return;
}
DataType dataType = dataPoint.getDataType();
for (Field field : dataType.getFields()) {
Value val = dataPoint.getValue(field);
if (dataType.equals(DataType.TYPE_STEP_COUNT_DELTA)) {
onStepTaken(val.asInt());
} else if (dataType.equals(DataType.TYPE_SPEED)) {
// Data comes in as meters per second, have to convert to minutes per mile.
float speedMetersPerSeconds = val.asFloat();
updateChallengePace(Utils.metersPerSecondToMinutesPerMile(speedMetersPerSeconds));
}
}
}
public void onStepTaken(int steps) {
mNumStepsSinceBeginningOfSample += steps;
mTotalNumStepsTaken += steps;
Utils.logDebug(TAG,
"Fit data update. You have now taken " + mTotalNumStepsTaken + " steps.");
// Update UI whenever a step is taken
Intent updateFitnessStatsIntent = new Intent();
updateFitnessStatsIntent.setAction(UPDATE_FITNESS_STATS);
getService().sendBroadcast(updateFitnessStatsIntent);
}
public int getNumSteps() {
return this.mTotalNumStepsTaken;
}
public float getMinutesPerMile() {
return this.mCurrentAverageMinutesPerMile;
}
public int getNumMinutesExercised() {
long timePassedNanos = mNowNanos - mMissionStartTimeNanos;
int timePassedSeconds = (int) Utils.nanosToSeconds(timePassedNanos);
int timePassedMinutes = timePassedSeconds / Utils.MINUTES_TO_SECONDS_SCALE;
return timePassedMinutes;
}
public int getNumSecondsExercised() {
long timePassedNanos = mNowNanos - mMissionStartTimeNanos;
int timePassedSeconds = (int) Utils.nanosToSeconds(timePassedNanos);
return timePassedSeconds % Utils.MINUTES_TO_SECONDS_SCALE;
}
public int getWeaponChargedPercentage() {
if (mIsWeaponCharged) {
return 100;
}
if (!mIsAtChallengePace) {
return 0;
}
long timeAtChallengePaceNanos = mNowNanos - mTimestampStartOfChallengePaceNanos;
float timeAtChallengePaceMinutes = Utils.nanosToMinutes(timeAtChallengePaceNanos);
float weaponChargedPercentage = timeAtChallengePaceMinutes
/ mData.getLengthOfIntervalMinutes() * 100;
return (int) weaponChargedPercentage;
}
public float getChallengePace() {
return mData.getChallengePaceMinutesPerMile();
}
public void onRebind() {
// Update UI after app wakes up (after the Activity is rebound to the Service)
Intent updateFitnessStatsIntent = new Intent();
updateFitnessStatsIntent.setAction(UPDATE_FITNESS_STATS);
getService().sendBroadcast(updateFitnessStatsIntent);
}
public static float getMaximumMinutesPerMile() {
return MAXIMUM_MINUTES_PER_MILE;
}
public ArrayList getFitnessStatistics() {
ArrayList fitnessStats = new ArrayList<>();
String numStepsTaken = String.format(getService()
.getString(R.string.fitness_stat_num_steps), mTotalNumStepsTaken);
fitnessStats.add(numStepsTaken);
String numIntervalsCompleted = String.format(getService()
.getString(R.string.fitness_stat_num_intervals), mTotalNumIntervalsCompleted);
fitnessStats.add(numIntervalsCompleted);
return fitnessStats;
}
private void calculateAverageMinutesPerMile() {
float timePassedSeconds = Utils.nanosToSeconds(mNowNanos - mSampleStartTimeNanos);
float timePassedMinutes = Utils.secondsToMinutes(timePassedSeconds);
float distanceTraveledFeet = mNumStepsSinceBeginningOfSample
* LENGTH_OF_RUNNING_STRIDE_FEET;
float distanceTraveledMiles = Utils.feetToMiles(distanceTraveledFeet);
if (distanceTraveledMiles > 0) {
updateChallengePace(timePassedMinutes / distanceTraveledMiles);
} else {
updateChallengePace(0.0f);
}
}
private void updateChallengePace(float averageMinutesPerMile) {
String updateText;
if (averageMinutesPerMile > 0) {
mCurrentAverageMinutesPerMile = averageMinutesPerMile;
updateText = (int)(mCurrentAverageMinutesPerMile)
+ getService().getString(R.string.log_message_minutes_per_mile);
} else {
mCurrentAverageMinutesPerMile = MAXIMUM_MINUTES_PER_MILE;
updateText = getService().getString(R.string.log_message_you_are_not_moving);
}
Utils.logDebug(TAG, updateText);
evaluateChallengePace();
// Reset start time and number of steps for next average speed sample.
mSampleStartTimeNanos = mNowNanos;
mNumStepsSinceBeginningOfSample = 0;
}
private void evaluateChallengePace() {
// Player is currently at challenge pace.
if (mCurrentAverageMinutesPerMile <= mData.getChallengePaceMinutesPerMile()) {
// At last check, player was not at challenge pace.
if (!mIsAtChallengePace) {
mService.queueSound(AT_CHALLENGE_PACE_URI, mService);
mTimestampStartOfChallengePaceNanos = mNowNanos;
}
// Player has been running at challenge pace for enough time to charge their weapon.
else if (!mIsWeaponCharged &&
Utils.nanosToMinutes(mNowNanos - mTimestampStartOfChallengePaceNanos)
>= mData.getLengthOfIntervalMinutes()) {
mService.queueSound(WEAPON_CHARGED_URI, mService);
mIsWeaponCharged = true;
mTotalNumIntervalsCompleted++;
}
mIsAtChallengePace = true;
}
// Player is not currently at challenge pace.
else {
// At last check, player was at challenge pace.
if (mIsAtChallengePace) {
mService.queueSound(NO_LONGER_AT_CHALLENGE_PACE_URI, mService);
}
mIsAtChallengePace = false;
}
}
private String getFitnessNotificationTitle() {
return getWeaponChargedPercentage()
+ getService().getString(R.string.weapon_status_notification_title);
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/MissionData.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import java.util.HashMap;
/**
* Encapsulates all of the game data that is necessary to represent a mission.
*/
public class MissionData {
private String mMissionName; // User-facing name of mission.
// ID must be unique to each mission
private String mMissionId;
private float mLengthOfMissionMinutes;
private float mLengthOfIntervalMinutes;
private float mChallengePaceMinutesPerMile;
private HashMap mAllMoments;
private String mFirstMomentId;
private String mCurrentMomentId;
/**
* Most general constructor. Used when wanting to construct most pieces of MissionData
* explicitly.
* @param missionId String identifying the Mission.
* @param lengthOfGameMinutes Total length of game.
* @param lengthOfIntervalMinutes Length of a running interval.
* @param allMoments HashMap containing all Moments that define this Mission.
* @param firstMomentId The first Moment to be executed during the Mission.
* @param currentMomentId The current Moment of the Mission.
*/
public MissionData(String missionName, String missionId, float lengthOfGameMinutes,
float lengthOfIntervalMinutes, float challengePaceMinutesPerMile,
HashMap allMoments, String firstMomentId, String currentMomentId) {
this.mMissionName = missionName;
this.mMissionId = missionId;
this.mLengthOfMissionMinutes = lengthOfGameMinutes;
this.mLengthOfIntervalMinutes = lengthOfIntervalMinutes;
this.mChallengePaceMinutesPerMile = challengePaceMinutesPerMile;
this.mAllMoments = allMoments;
this.mFirstMomentId = firstMomentId;
this.mCurrentMomentId = currentMomentId;
}
/**
* Constructor used when populating MissionData with information from menu screens.
* @param missionId String identifying the Mission.
* @param lengthOfGameMinutes Total length of game.
* @param lengthOfIntervalMinutes Length of a running interval.
*/
public MissionData(String missionName, String missionId, float lengthOfGameMinutes,
float lengthOfIntervalMinutes, float challengePaceMinutesPerMile) {
this(missionName, missionId, lengthOfGameMinutes, lengthOfIntervalMinutes,
challengePaceMinutesPerMile, new HashMap(), null, null);
}
public String getMissionName() {
return this.mMissionName;
}
public String getMissionId() {
return this.mMissionId;
}
public float getLengthOfMissionMinutes() {
return this.mLengthOfMissionMinutes;
}
public float getLengthOfIntervalMinutes() {
return this.mLengthOfIntervalMinutes;
}
public float getChallengePaceMinutesPerMile() {
return this.mChallengePaceMinutesPerMile;
}
public Moment getMomentFromId(String momentId) {
return mAllMoments.get(momentId);
}
public String getCurrentMomentId() {
return this.mCurrentMomentId;
}
public String getFirstMomentId() {
return this.mFirstMomentId;
}
public void setCurrentMomentId(String currentMomentId) {
this.mCurrentMomentId = currentMomentId;
}
public void addMoment(String momentId, Moment moment) {
this.mAllMoments.put(momentId, moment);
}
public void setFirstMomentId(String firstMomentId) {
this.mFirstMomentId = firstMomentId;
}
public Moment getCurrentMoment() {
return mAllMoments.get(mCurrentMomentId);
}
public int getNumMoments() {
return mAllMoments.size();
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/Moment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.util.ArrayList;
/**
* A Moment is a discrete event within a Mission. Moments know when they are finished ('isDone()'),
* and they are never reused.
*/
public abstract class Moment {
// The mission to which this moment belongs.
private Mission mMission;
public boolean mIsDone;
private boolean mShouldRestart;
private long mTimeWhenRestartRequestedNanos;
private long mRestartDelayLengthNanos;
/**
* @param mission The Mission to which this moment belongs. Cannot be changed after
* instantiation - each Moment is irrevocably associated with a Mission.
*/
protected Moment(Mission mission) {
this.mMission = mission;
}
public Mission getMission() {
return mMission;
}
/**
* Called on the current moment to determine if it is appropriate to move on.
* @return true if this moment no longer should be active as the current moment.
*/
public boolean isDone() {
return mIsDone;
}
public void setIsDone(boolean isDone) {
this.mIsDone = isDone;
}
/**
* Update the moment information for the current time. Default behavior checks if the Moment
* should restart, and does.
* @param nowNanos The current time, represented in nanoseconds.
*/
public void update(long nowNanos) {
if (mShouldRestart
&& nowNanos > mTimeWhenRestartRequestedNanos + mRestartDelayLengthNanos) {
restart(nowNanos);
}
}
/**
* Read the id of the next Moment associated with this Moment.
* @return String identifying the next Moment associated with this Moment.
*/
public abstract String getNextMomentId();
/**
* Make this moment active. Runs when the moment begins.
* @param nowNanos The current time, represented in nanoseconds.
*/
public void start(long nowNanos) {
this.mIsDone = false;
this.mShouldRestart = false;
}
/**
* Ends the current moment.
*/
public abstract void end();
/**
* Restarts a moment.
*/
public abstract void restart(long nowNanos);
public void restartWithDelay(long nowNanos, float secondsDelayRestart) {
mShouldRestart = true;
mTimeWhenRestartRequestedNanos = nowNanos;
mRestartDelayLengthNanos = Utils.secondsToNanos(secondsDelayRestart);
}
public abstract ArrayList getFictionalProgress();
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/MomentData.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import java.util.ArrayList;
/**
* Encapsulates the data that is needed to define a unique Moment.
*/
public abstract class MomentData {
// The id of this moment. Must be unique across the moments in the mission.
private final String mMomentId;
// The moment to go to next.
private final String mNextMomentId;
private ArrayList mFictionalProgress;
/**
* Constructor to explicitly set all fields for a ChoiceMomentData.
* @param momentId Identifier for the ChoiceMoment.
* @param nextMomentId The moment following this one. Null if is the last moment in a mission.
* @param fictionalProgress Fictional progress for this moment.
*/
public MomentData(String momentId, String nextMomentId, ArrayList fictionalProgress) {
mMomentId = momentId;
mNextMomentId = nextMomentId;
mFictionalProgress = fictionalProgress;
}
public String getMomentId() {
return mMomentId;
}
public String getNextMomentId() {
return mNextMomentId;
}
public ArrayList getFictionalProgress() {
return mFictionalProgress;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/Outcome.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
/**
* Encapsulates the game data changes that should occur as a result of a certain Choice
*/
public class Outcome {
private boolean mDepleteWeaponCharge;
private boolean mIncrementNumEnemiesDefeated;
public Outcome(boolean depleteWeaponCharge, boolean incrementNumEnemiesDefeated) {
this.mDepleteWeaponCharge = depleteWeaponCharge;
this.mIncrementNumEnemiesDefeated = incrementNumEnemiesDefeated;
}
public boolean weaponChargeDepleted() {
return this.mDepleteWeaponCharge;
}
public boolean numEnemiesDefeatedIncremented() {
return this.mIncrementNumEnemiesDefeated;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/SfxMoment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import android.media.MediaPlayer;
import java.io.IOException;
import java.util.ArrayList;
/**
* Describes a Moment in which the user listens to a pre-recorded sound effect as part of the
* gameplay.
*/
public class SfxMoment extends Moment implements MediaPlayer.OnCompletionListener {
private SfxMomentData mData;
public SfxMoment(Mission mission, SfxMomentData data) {
super(mission);
this.mData = data;
}
@Override
public void start(long nowNanos) {
super.start(nowNanos);
getMission().getService().queueSound(mData.getUriAsset(), this);
}
@Override
public void end() {
}
@Override
public String getNextMomentId() {
return mData.getNextMomentId();
}
/**
* We need to know when our specific sfx is done playing. Then we fallback to the default
* onCompletionListener to finish cleaning up.
*/
@Override
public void onCompletion(MediaPlayer mp) {
setIsDone(true);
getMission().getService().onCompletion(mp);
}
@Override
public void restart(long nowNanos) {
getMission().getService().dequeueSound(mData.getUriAsset());
// Try to start again.
start(nowNanos);
}
public SfxMomentData getMomentData() {
return this.mData;
}
@Override
public ArrayList getFictionalProgress() {
return mData.getFictionalProgress();
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/SfxMomentData.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import android.net.Uri;
import java.util.ArrayList;
/**
* Encapsulates the data that is needed to define a unique NotificationAudioMoment.
*/
public class SfxMomentData extends MomentData {
// The name of the sound file to play
private final Uri mUriAsset;
/**
* Constructor to explicitly set all fields for a ChoiceMomentData.
* @param momentId Identifier for the ChoiceMoment.
* @param nextMomentId The moment following this one. Null if is the last moment in a mission.
* @param fictionalProgress Fictional progress for this moment.
* @param uriAsset Uri of the sound to play with this moment.
*/
public SfxMomentData(String momentId, String nextMomentId,
ArrayList fictionalProgress, Uri uriAsset) {
super(momentId, nextMomentId, fictionalProgress);
mUriAsset = uriAsset;
}
public Uri getUriAsset() {
return mUriAsset;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/SpokenTextMoment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Describes a Moment in which the user listens to a piece of fiction as part of the gameplay.
* The fiction will be read aloud using Android's text-to-speech capabilities.
*/
public class SpokenTextMoment extends Moment {
private static final String TAG = SpokenTextMoment.class.getSimpleName();
private SpokenTextMomentData mData;
private static final float RETRY_WAIT_TIME_SECONDS = 2.5f;
// Buffer time before speaking with TextToSpeech.
private static final long SILENCE_LENGTH_MILLIS = 500;
// Determines behavior to execute during TextToSpeech speaking.
private UtteranceProgressListener mUtteranceProgressListener = new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
}
@Override
/**
* Determines behavior when TextToSpeech has completed speaking, or stopped.
*/
public void onDone(String utteranceId) {
setIsDone(true);
getMission().getService().endPlayback();
}
@Override
public void onError(String utteranceId) {
}
};
public SpokenTextMoment(Mission mission, SpokenTextMomentData data) {
super(mission);
this.mData = data;
}
@Override
public void start(long nowNanos) {
super.start(nowNanos);
Utils.logDebug(TAG, "SpokenTextMoment \"" + mData.getMomentId() + "\" started.");
if (getMission().getService().obtainAudioFocus()) {
speak();
} else {
// Try again at a future time.
restartWithDelay(nowNanos, RETRY_WAIT_TIME_SECONDS);
}
}
@Override
public void end() {
Utils.logDebug(TAG, "SpokenTextMoment \"" + mData.getMomentId() + "\" ended.");
getMission().getService().getTextToSpeech().setOnUtteranceProgressListener(null);
getMission().getService().getTextToSpeech().stop();
}
public String getNextMomentId() {
return mData.getNextMomentId();
}
/**
* Use TextToSpeech to say the words associated with this Moment.
*/
private void speak() {
TextToSpeech textToSpeech = getMission().getService().getTextToSpeech();
textToSpeech.setOnUtteranceProgressListener(mUtteranceProgressListener);
textToSpeech.playSilence(SILENCE_LENGTH_MILLIS, TextToSpeech.QUEUE_ADD, null);
HashMap map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, mData.getMomentId());
textToSpeech.speak(mData.getTextToSpeak(), TextToSpeech.QUEUE_ADD, map);
}
@Override
public void restart(long nowNanos) {
// Stop anything in progress.
end();
start(nowNanos);
}
public SpokenTextMomentData getMomentData() {
return this.mData;
}
@Override
public ArrayList getFictionalProgress() {
return mData.getFictionalProgress();
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/SpokenTextMomentData.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import java.util.ArrayList;
/**
* Encapsulates the data that is needed to define a unique FictionAudioMoment.
*/
public class SpokenTextMomentData extends MomentData {
// The text to be read aloud using text-to-speech
private final String mTextToSpeak;
/**
* Constructor to explicitly set all fields for a ChoiceMomentData.
* @param momentId Identifier for the ChoiceMoment.
* @param nextMomentId The moment following this one. Null if is the last moment in a mission.
* @param fictionalProgress Fictional progress for this moment.
* @param textToSpeak Words associated with this moment.
*/
public SpokenTextMomentData(String momentId, String nextMomentId,
ArrayList fictionalProgress, String textToSpeak) {
super(momentId, nextMomentId, fictionalProgress);
mTextToSpeak = textToSpeak;
}
public String getTextToSpeak() {
return mTextToSpeak;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/TimerMoment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.util.ArrayList;
/**
* Describes a Moment in which there is a gap in gameplay for a given amount of time.
*/
public class TimerMoment extends Moment {
private static final String TAG = TimerMoment.class.getSimpleName();
private TimerMomentData mData;
private long mStartTimeNanos;
public TimerMoment(Mission mission, TimerMomentData data) {
super(mission);
this.mData = data;
}
@Override
public void update(long nowNanos) {
setIsDone(hasMomentTimeElapsed(nowNanos));
}
@Override
public void start(long nowNanos) {
super.start(nowNanos);
Utils.logDebug(TAG, "TimerMoment \"" + mData.getMomentId() + "\" started.");
setStartTimeNanos(nowNanos);
}
@Override
public void end() {
Utils.logDebug(TAG, "TimerMoment \"" + mData.getMomentId() + "\" ended.");
}
/**
* Determines if the TimerMoment has elapsed.
* @param nowNanos The current time.
* @return True if the time since the TimerMoment started is greater than or equal to the length
* of the timer moment.
*/
public boolean hasMomentTimeElapsed(long nowNanos) {
return (nowNanos - mStartTimeNanos) >= Utils.minutesToNanos(mData.getLengthMinutes());
}
public void setStartTimeNanos(long startTimeNanos) {
this.mStartTimeNanos = startTimeNanos;
}
@Override
public String getNextMomentId() {
return mData.getNextMomentId();
}
@Override
public void restart(long nowNanos) {
// No additional tear down or resetting necessary.
start(nowNanos);
}
public TimerMomentData getMomentData() {
return this.mData;
}
@Override
public ArrayList getFictionalProgress() {
return mData.getFictionalProgress();
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/TimerMomentData.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame;
import java.util.ArrayList;
/**
* Encapsulates the data that is needed to define a unique TimerMoment.
*/
public class TimerMomentData extends MomentData {
// The length of the timer in minutes
private float mLengthMinutes;
/**
* Constructor to explicitly set all fields for a ChoiceMomentData.
* @param momentId Identifier for the ChoiceMoment.
* @param nextMomentId The moment following this one. Null if is the last moment in a mission.
* @param fictionalProgress Fictional progress for this moment.
* @param lengthMinutes Length of this moment.
*/
public TimerMomentData(String momentId, String nextMomentId,
ArrayList fictionalProgress, float lengthMinutes) {
super(momentId, nextMomentId, fictionalProgress);
mLengthMinutes = lengthMinutes;
}
public float getLengthMinutes() {
return mLengthMinutes;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/google/FitDataTypeSetting.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.google;
import com.google.android.gms.fitness.data.DataType;
/**
* This keeps track of the sensor data types and their registration settings.
*/
public class FitDataTypeSetting {
private boolean mRequired; // Is this data type required for the game to start?
private DataType mDataType;
private long mSamplingRateSeconds;
private int mAccuracyMode;
public FitDataTypeSetting(
boolean required, DataType dataType, long samplingRateSeconds, int accuracyMode) {
mRequired = required;
mDataType = dataType;
mSamplingRateSeconds = samplingRateSeconds;
mAccuracyMode = accuracyMode;
}
public boolean isRequired() {
return mRequired;
}
public DataType getDataType() {
return mDataType;
}
public long getSamplingRateSeconds() {
return mSamplingRateSeconds;
}
public int getAccuracyMode() {
return mAccuracyMode;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/google/FitResultCallback.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.google;
import android.util.Log;
import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.FitnessStatusCodes;
import com.google.android.gms.fitness.data.DataType;
import com.google.fpl.gim.examplegame.utils.Utils;
/**
* Implements ResultCallback while allowing to record more state so we can change game flow
* accordingly.
*/
public class FitResultCallback
implements com.google.android.gms.common.api.ResultCallback {
private static final String TAG = "GoogleFitResultCallback";
// Enum type for keeping track of which API generated this callback.
public enum RegisterType {
SENSORS,
RECORDING,
SESSION,
}
GoogleApiClientWrapper mGoogleApiClient;
RegisterType mRegisterType;
DataType mDataType;
boolean mSubscribe; // True if subscribe, false if unsubscribe.
/**
* Default constructor.
* @param googleApiClient The GoogleApiClientWrapper to pass data back to.
* @param registerType The type of call that resulted in this callback.
* @param dataType The data type we are trying to process.
* @param subscribe If true, this is a subscribe or a register call.
*/
public FitResultCallback(
GoogleApiClientWrapper googleApiClient, RegisterType registerType, DataType dataType,
boolean subscribe) {
mGoogleApiClient = googleApiClient;
mRegisterType = registerType;
mDataType = dataType;
mSubscribe = subscribe;
}
@Override
public void onResult(R result) {
switch (mRegisterType) {
case SENSORS:
onSensorResult(result.getStatus());
break;
case RECORDING:
onRecordingResult(result.getStatus());
break;
case SESSION:
onSessionResult(result.getStatus());
break;
default:
Log.e(TAG, "Unknown enum type.");
}
}
private void onSensorResult(Status status) {
if (status.isSuccess()) {
// There is a lapse between this callback to actually getting data from the listener,
// depending on the data type. It is a known issue, by design. You can account for that
// delay with display text or other mechanisms.
mGoogleApiClient.sensorRegistered(mDataType);
Utils.logDebug(TAG, "Successfully registered sensor for " + mDataType.toString());
} else {
Utils.logDebug(TAG, "There was a problem registering ." + mDataType + "\n" +
status.getStatusMessage());
}
}
private void onRecordingResult(Status status) {
if (mSubscribe) {
onRecordingSubscription(status);
} else {
onRecordingUnsubscription(status);
}
}
private void onRecordingSubscription(Status status) {
if (status.isSuccess()) {
if (status.getStatusCode()
== FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
Utils.logDebug(TAG, "Existing subscription for activity detected.");
} else {
Utils.logDebug(TAG, "Started recording data for " + mDataType);
}
} else {
// For a better user experience, you can add visual error text indicating the session
// will not be recorded to the cloud.
Utils.logDebug(TAG, "Unable to start recording data for " + mDataType);
}
}
private void onRecordingUnsubscription(Status status) {
if (status.isSuccess()) {
Utils.logDebug(TAG, "Stopped recording data for " + mDataType);
} else {
Utils.logDebug(TAG, "Unable to stop recording data for " + mDataType);
}
}
private void onSessionResult(Status status) {
if (mSubscribe) {
onSessionSubscription(status);
} else {
onSessionUnsubscription(status);
}
}
private void onSessionSubscription(Status status) {
if (status.isSuccess()) {
Utils.logDebug(TAG, "Started data session.");
} else {
// For a better user experience, you can add visual error text indicating the session
// will not be identified in the cloud.
Utils.logDebug(TAG, "Unable to start data session.");
}
}
private void onSessionUnsubscription(Status status) {
if (status.isSuccess()) {
Utils.logDebug(TAG, "Ended data session.");
} else {
Utils.logDebug(TAG, "Unable to end data session.");
}
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/google/GoogleApiClientWrapper.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.google;
import android.app.Activity;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessActivities;
import com.google.android.gms.fitness.FitnessStatusCodes;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Session;
import com.google.android.gms.fitness.request.OnDataPointListener;
import com.google.android.gms.fitness.request.SensorRequest;
import com.google.android.gms.fitness.result.SessionStopResult;
import com.google.android.gms.games.Games;
import com.google.fpl.gim.examplegame.MainActivity;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Container class to hold a static instance of GoogleApiClient. This allows the MainActivity
* class to implement the GoogleApiClient.OnConnectionFailedListener interface (which
* requires an Activity to request authentications from the user) and the MainService class to
* implement the GoogleApiClient.ConnectionCallbacks interface. This also allows the Google
* API client to be subsequently accessed by either class.
*/
public class GoogleApiClientWrapper implements ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = GoogleApiClientWrapper.class.getSimpleName();
private static final String SESSION_NAME = "Games-in-Motion Mission";
public static final int REQUEST_CODE_OAUTH = 1;
private boolean mAuthInProgress = false;
private Activity mActivity; // Activity for GoogleApiClient to launch visual elements on.
private GoogleApiClient mGoogleApiClient;
private Set sensorsAwaitingRegistration = new HashSet<>();
/**
* Builds a GoogleApiClient that connects to the Fitness Api.
* @param activity The activity through which authorization UI will be launched.
*/
public void buildGoogleApiClient(Activity activity) {
if (mGoogleApiClient != null) {
return;
}
Utils.logDebug(TAG, "Building the Google Api Client.");
mActivity = activity;
// Create the Google API Client.
mGoogleApiClient = new GoogleApiClient.Builder(activity, this, this)
.addApi(Fitness.API) // Fitness API
.addScope(Fitness.SCOPE_ACTIVITY_READ) // Fitness Scopes
.addScope(Fitness.SCOPE_LOCATION_READ)
.addApi(Games.API) // Games API
.addScope(Games.SCOPE_GAMES) // Games Scope
.build();
}
public void connect() {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle connectionHint) {
Utils.logDebug(TAG, "Connected!");
// Send the hint to Activity for UI updates
((MainActivity) mActivity).onFitStatusUpdated(true);
}
@Override
public void onConnectionSuspended(int i) {
// If your connection gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Utils.logDebug(TAG, "Connection lost. Cause: Network Lost.");
} else if (i == ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Utils.logDebug(TAG, "Connection lost. Reason: Service Disconnected");
}
// Send the hint to Activity for UI updates
((MainActivity) mActivity).onFitStatusUpdated(false);
// Attempt to reconnect
connect();
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.e(TAG, "Connection failed. Cause: " + result.toString());
if (!result.hasResolution()) {
// Show the localized error dialog
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), mActivity, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization dialog is displayed to the user.
if (!mAuthInProgress && (result.getErrorCode() == ConnectionResult.SIGN_IN_REQUIRED
|| result.getErrorCode() == FitnessStatusCodes.NEEDS_OAUTH_PERMISSIONS)) {
try {
Utils.logDebug(TAG, "Attempting to resolve failed connection");
mAuthInProgress = true;
result.startResolutionForResult(mActivity, REQUEST_CODE_OAUTH);
} catch (IntentSender.SendIntentException e) {
mAuthInProgress = false;
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
}
/**
* Starts a new session for Fit data. This will take care of registering all the sensors,
* recording the sensor data, and registering the data set as a session to Google Fit.
* @param dataTypeSettings Types of data to listen to, in an array.
* @param sessionDescription The description of the session.
* @param listener The OnDataPointListener to receive sensor events.
*/
public void startFitDataSession(FitDataTypeSetting[] dataTypeSettings,
String sessionDescription, OnDataPointListener listener) {
for (FitDataTypeSetting dataTypeSetting : dataTypeSettings) {
registerFitDataListener(dataTypeSetting, listener);
startRecordingFitData(dataTypeSetting);
}
Session session = new Session.Builder()
.setName(SESSION_NAME)
.setDescription(sessionDescription)
.setActivity(FitnessActivities.RUNNING_JOGGING)
.setStartTime(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.build();
PendingResult pendingResult =
Fitness.SessionsApi.startSession(mGoogleApiClient, session);
pendingResult.setResultCallback(new FitResultCallback(
this, FitResultCallback.RegisterType.SESSION, null /* dataType */,
true /* subscribe */));
}
/**
* Ends the session for Fit data. This will take care of un-registering all the sensors,
* stop recording the sensor data, and stop recording the data set as a session to Google Fit.
* @param dataTypeSettings Types of data to listen to, in an array.
* @param listener The OnDataPointListener to receive sensor events.
*/
public void endFitDataSession(
FitDataTypeSetting[] dataTypeSettings, OnDataPointListener listener) {
if (mGoogleApiClient.isConnected()) {
PendingResult pendingResult =
Fitness.SessionsApi.stopSession(mGoogleApiClient, null);
pendingResult.setResultCallback(new FitResultCallback(
this, FitResultCallback.RegisterType.SESSION, null /* dataType */,
false /* subscribe */));
for (FitDataTypeSetting dataTypeSetting : dataTypeSettings) {
stopRecordingFitData(dataTypeSetting);
unregisterFitDataListener(listener);
}
}
}
public boolean isSignedIn() {
return (mGoogleApiClient != null && mGoogleApiClient.isConnected());
}
public void userAuthenticated() {
mAuthInProgress = false;
}
public boolean isClientReady() {
// Make sure all the required sensors are registered.
boolean hasUnregisteredSensor = false;
for (FitDataTypeSetting fitDataTypeSetting : sensorsAwaitingRegistration) {
if (fitDataTypeSetting.isRequired()) {
hasUnregisteredSensor = true;
break;
}
}
return (mGoogleApiClient.isConnected() && !hasUnregisteredSensor);
}
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
protected void sensorRegistered(DataType dataType) {
for (FitDataTypeSetting fitDataTypeSetting : sensorsAwaitingRegistration) {
if (fitDataTypeSetting.getDataType().equals(dataType)) {
sensorsAwaitingRegistration.remove(fitDataTypeSetting);
break;
}
}
}
/**
* Add RecordingApi listener for recording to GoogleFit backend. Can be called repeatedly on
* multiple data types.
* @param dataTypeSetting Type of data to listen to.
*/
private void startRecordingFitData(FitDataTypeSetting dataTypeSetting) {
Fitness.RecordingApi.subscribe(mGoogleApiClient, dataTypeSetting.getDataType())
.setResultCallback(new FitResultCallback(
this, FitResultCallback.RegisterType.RECORDING,
dataTypeSetting.getDataType(), true));
}
private void stopRecordingFitData(FitDataTypeSetting dataTypeSetting) {
Fitness.RecordingApi.unsubscribe(mGoogleApiClient, dataTypeSetting.getDataType())
.setResultCallback(new FitResultCallback(
this, FitResultCallback.RegisterType.RECORDING,
dataTypeSetting.getDataType(), false));
}
/**
* Add SensorsApi listener for real-time display of sensor data. Can be called repeatedly on
* multiple data types.
* @param dataTypeSetting Type of data to listen to.
* @param listener Listener for callbacks from SensorsApi.
*/
private void registerFitDataListener(
FitDataTypeSetting dataTypeSetting, OnDataPointListener listener) {
sensorsAwaitingRegistration.add(dataTypeSetting);
Fitness.SensorsApi.add(
mGoogleApiClient,
new SensorRequest.Builder()
.setDataType(dataTypeSetting.getDataType())
.setSamplingRate(dataTypeSetting.getSamplingRateSeconds(), TimeUnit.SECONDS)
.setAccuracyMode(dataTypeSetting.getAccuracyMode())
.build(),
listener)
.setResultCallback(new FitResultCallback(
this, FitResultCallback.RegisterType.SENSORS, dataTypeSetting.getDataType(),
true));
}
private void unregisterFitDataListener(OnDataPointListener listener) {
Fitness.SensorsApi.remove(mGoogleApiClient, listener);
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/EndSummaryFragment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.gui;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.fpl.gim.examplegame.MainActivity;
import com.google.fpl.gim.examplegame.R;
import java.util.ArrayList;
/**
* Displays post-run summary.
*/
public class EndSummaryFragment extends Fragment {
private ListView mFictionalProgressList;
private ListView mFitnessStatisticsList;
private boolean mGoogleFitConnected = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.end_screen, container, false);
mFictionalProgressList = (ListView) rootView.findViewById(R.id.fictionalProgressList);
mFitnessStatisticsList = (ListView) rootView.findViewById(R.id.fitnessStatisticsList);
return rootView;
}
@Override public void onResume() {
super.onResume();
if (mGoogleFitConnected) {
((MainActivity) getActivity()).setActionBarTitle(R.string.run_finish_text);
} else {
((MainActivity) getActivity()).setActionBarTitle(R.string.fit_disconnected_text);
}
}
public void displayStats(ArrayList fictionalProgress,
ArrayList fitnessStatistics) {
mFictionalProgressList.setAdapter(new ArrayAdapter<>(getActivity(),
R.layout.menu_list_item, R.id.list_item_text, fictionalProgress));
mFitnessStatisticsList.setAdapter(new ArrayAdapter<>(getActivity(),
R.layout.menu_list_item, R.id.list_item_text, fitnessStatistics));
}
public void onFitStatusUpdated(boolean connected) {
mGoogleFitConnected = connected;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/FitnessDataDisplayFragment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.gui;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.fpl.gim.examplegame.MainActivity;
import com.google.fpl.gim.examplegame.Mission;
import com.google.fpl.gim.examplegame.R;
/**
* Display fitness data during a run.
*/
public class FitnessDataDisplayFragment extends Fragment {
private TextView mNumSteps;
private TextView mMinutesPerMile;
private TextView mTimeExercised;
private TextView mWeaponChargedPercentage;
private ProgressBar mProgressBar;
private String mMissionName = "Mission";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.step_display, container, false);
mNumSteps = (TextView) rootView.findViewById(R.id.num_steps_taken);
mMinutesPerMile = (TextView) rootView.findViewById(R.id.minutes_per_mile);
mTimeExercised = (TextView) rootView.findViewById(R.id.time_exercised);
mWeaponChargedPercentage = (TextView) rootView.findViewById(R.id.percent_weapon_charged);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.circular_progress_bar);
mProgressBar.setMax(100);
mProgressBar.setProgress(0);
return rootView;
}
@Override public void onResume() {
super.onResume();
((MainActivity)getActivity()).setActionBarTitle(mMissionName);
}
public void setNumSteps(int numSteps) {
mNumSteps.setText(String.format("%d steps", numSteps));
}
public void setMinutesPerMile(float minutesPerMile, float challengePace) {
if (minutesPerMile >= Mission.getMaximumMinutesPerMile()) {
mMinutesPerMile.setText(getActivity().getString(R.string.not_moving_speed));
} else {
String minutesPerMileText = String.format("%.2f\nmins/mile", minutesPerMile);
mMinutesPerMile.setText(minutesPerMileText);
if (minutesPerMile <= challengePace) {
mMinutesPerMile.setTextColor(getResources().getColor(R.color.green));
} else {
mMinutesPerMile.setTextColor(getResources().getColor(R.color.red));
}
}
}
public void setTimeExercised(int numMinutes, int numSeconds) {
mTimeExercised.setText(String.format("%d:%02d", numMinutes, numSeconds));
}
public void setWeaponChargedPercentage(int weaponChargedPercentage) {
mWeaponChargedPercentage.setText(String.format("%d%%", weaponChargedPercentage));
mProgressBar.setProgress(weaponChargedPercentage);
}
public void setFitnessStats(Mission mission) {
setNumSteps(mission.getNumSteps());
setMinutesPerMile(mission.getMinutesPerMile(), mission.getChallengePace());
setTimeExercised(mission.getNumMinutesExercised(), mission.getNumSecondsExercised());
setWeaponChargedPercentage(mission.getWeaponChargedPercentage());
}
public void setMissionName(String missionName) {
mMissionName = missionName;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/GameViews.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.gui;
import android.app.Activity;
import com.google.fpl.gim.examplegame.R;
import com.google.fpl.gim.examplegame.gui.EndSummaryFragment;
import com.google.fpl.gim.examplegame.gui.FitnessDataDisplayFragment;
import com.google.fpl.gim.examplegame.gui.MissionSelectionFragment;
import com.google.fpl.gim.examplegame.gui.MusicSelectionFragment;
import com.google.fpl.gim.examplegame.gui.RunSpecificationSelectionFragment;
import com.google.fpl.gim.examplegame.gui.StartMenuFragment;
/**
* Container for the game's UI Fragments. This class is implemented as a singleton to ensure that
* only one instance of the GameViews class ever exists.
*/
public class GameViews {
// Tags used to save/restore Fragments.
public static final String START_MENU_TAG =
"com.google.fpl.gim.examplegame.fragment.StartMenuFragment";
public static final String LIST_OF_MISSIONS_TAG =
"com.google.fpl.gim.examplegame.ListOfMissionsFragment";
public static final String RUN_SPECIFICATIONS_TAG =
"com.google.fpl.gim.examplegame.RunSpecificationsFragment";
public static final String MUSIC_SELECTION_TAG =
"com.google.fpl.gim.examplegame.fragment.MusicSelectionFragment";
public static final String END_SUMMARY_TAG =
"com.google.fpl.gim.examplegame.fragment.EndSummaryFragment";
public static final String FITNESS_DATA_DISPLAY_TAG =
"com.google.fpl.gim.examplegame.fragment.FitnessDataDisplayFragment";
// UI Fragments.
private StartMenuFragment mStartMenuFragment;
private MissionSelectionFragment mMissionSelectionFragment;
private RunSpecificationSelectionFragment mRunSpecificationsFragment;
private MusicSelectionFragment mMusicSelectionFragment;
private EndSummaryFragment mEndSummaryFragment;
private FitnessDataDisplayFragment mFitnessDataDisplayFragment;
public GameViews() {
}
/**
* Called the first time upon starting the game by the 'initializeFragments' method in the Game
* class. Creates fragments and attaches them to the Activity.
*/
public void initializeFragments(Activity activity) {
mStartMenuFragment = new StartMenuFragment();
activity.getFragmentManager().beginTransaction()
.add(R.id.container, mStartMenuFragment, START_MENU_TAG)
.addToBackStack(START_MENU_TAG)
.commit();
mStartMenuFragment.setRetainInstance(true);
mMissionSelectionFragment = new MissionSelectionFragment();
mMissionSelectionFragment.setRetainInstance(true);
mRunSpecificationsFragment = new RunSpecificationSelectionFragment();
mRunSpecificationsFragment.setRetainInstance(true);
mMusicSelectionFragment = new MusicSelectionFragment();
mMusicSelectionFragment.setRetainInstance(true);
mEndSummaryFragment = new EndSummaryFragment();
mEndSummaryFragment.setRetainInstance(true);
mFitnessDataDisplayFragment = new FitnessDataDisplayFragment();
mFitnessDataDisplayFragment.setRetainInstance(true);
}
/**
* Restores information and fragments from the Bundle upon lifecycle restart. Called
* by the 'restoreFragments' method in the Game class.
*/
public void restoreFragments(Activity activity) {
StartMenuFragment foundStartMenuFragment = (StartMenuFragment) activity.getFragmentManager()
.findFragmentByTag(START_MENU_TAG);
if (foundStartMenuFragment != null) {
mStartMenuFragment = foundStartMenuFragment;
} else {
mStartMenuFragment = new StartMenuFragment();
}
MissionSelectionFragment foundMissionSelectionFragment =
(MissionSelectionFragment) activity.getFragmentManager()
.findFragmentByTag(LIST_OF_MISSIONS_TAG);
if (foundMissionSelectionFragment != null) {
mMissionSelectionFragment = foundMissionSelectionFragment;
} else {
mMissionSelectionFragment = new MissionSelectionFragment();
}
RunSpecificationSelectionFragment foundRunSpecificationSelectionFragment =
(RunSpecificationSelectionFragment) activity.getFragmentManager()
.findFragmentByTag(RUN_SPECIFICATIONS_TAG);
if (foundRunSpecificationSelectionFragment != null) {
mRunSpecificationsFragment = foundRunSpecificationSelectionFragment;
} else {
mRunSpecificationsFragment = new RunSpecificationSelectionFragment();
}
MusicSelectionFragment foundMusicSelectionFragment =
(MusicSelectionFragment) activity.getFragmentManager()
.findFragmentByTag(MUSIC_SELECTION_TAG);
if (foundMissionSelectionFragment != null) {
mMusicSelectionFragment = foundMusicSelectionFragment;
} else {
mMusicSelectionFragment = new MusicSelectionFragment();
}
EndSummaryFragment foundEndSummaryFragment =
(EndSummaryFragment) activity.getFragmentManager()
.findFragmentByTag(END_SUMMARY_TAG);
if (foundEndSummaryFragment != null) {
mEndSummaryFragment = foundEndSummaryFragment;
} else {
mEndSummaryFragment = new EndSummaryFragment();
}
FitnessDataDisplayFragment foundFitnessDataDisplayFragment =
(FitnessDataDisplayFragment) activity.getFragmentManager()
.findFragmentByTag(FITNESS_DATA_DISPLAY_TAG);
if (foundFitnessDataDisplayFragment != null) {
mFitnessDataDisplayFragment = foundFitnessDataDisplayFragment;
} else {
mFitnessDataDisplayFragment = new FitnessDataDisplayFragment();
}
}
public StartMenuFragment getStartMenuFragment() {
return this.mStartMenuFragment;
}
public MissionSelectionFragment getListOfMissionsFragment() {
return mMissionSelectionFragment;
}
public RunSpecificationSelectionFragment getRunSpecificationsFragment() {
return mRunSpecificationsFragment;
}
public MusicSelectionFragment getMusicSelectionFragment() {
return mMusicSelectionFragment;
}
public EndSummaryFragment getEndSummaryFragment() {
return mEndSummaryFragment;
}
public FitnessDataDisplayFragment getFitnessDataDisplayFragment() {
return mFitnessDataDisplayFragment;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/MissionSelectionFragment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.gui;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.fpl.gim.examplegame.MainActivity;
import com.google.fpl.gim.examplegame.utils.MissionParseException;
import com.google.fpl.gim.examplegame.utils.MissionParser;
import com.google.fpl.gim.examplegame.R;
import com.google.fpl.gim.examplegame.utils.Utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* A UI fragment that represents the game's mission selection screen. No data is stored in this
* fragment.
*/
public class MissionSelectionFragment extends ListFragment {
private static final String TAG = MissionSelectionFragment.class.getSimpleName();
private ArrayList mAssetNames = new ArrayList<>();
private ArrayList mMissionNames = new ArrayList<>();
private String mSelectedMissionName;
private String mSelectedAssetPath;
private static final String MISSION_ASSET_FOLDER_NAME = "missions";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mMissionNames.size() == 0) {
// Needs access to a Context in order to access the assets folder.
AssetManager assetManager = getActivity().getAssets();
String[] missionFileNames = new String[0];
try {
// Obtain the files in assets/missions.
missionFileNames = assetManager.list(MISSION_ASSET_FOLDER_NAME);
} catch (IOException e) {
e.printStackTrace();
}
// Open the missions to obtain plain text names.
for (String missionFileName : missionFileNames) {
// Open a stream for the mission.
InputStream stream;
try {
// All missions should be in the assets/missions folder.
ArrayList subDirectories = new ArrayList<>();
subDirectories.add(missionFileName);
stream = assetManager
.open(Utils.makeFilePath(MISSION_ASSET_FOLDER_NAME, subDirectories));
} catch (IOException e) {
e.printStackTrace();
continue;
}
// Find the mission name.
String missionName;
try {
missionName = MissionParser.getMissionName(stream);
} catch (MissionParseException e) {
e.printStackTrace();
missionName = "Description failed.";
}
// Close the stream.
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
mMissionNames.add(missionName);
mAssetNames.add(missionFileName);
}
}
setListAdapter(new ArrayAdapter<>(getActivity(), R.layout.menu_list_item,
R.id.list_item_text, mMissionNames));
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.menu_mission_list, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
onMissionSelected(position);
}
@Override public void onResume() {
super.onResume();
((MainActivity)getActivity()).setActionBarTitle(R.string.select_mission_title);
}
public void onMissionSelected(int position) {
Utils.logDebug(TAG, "onMissionSelected - Mission #" + (position + 1) +
" has been selected!");
mSelectedMissionName = mMissionNames.get(position);
ArrayList subDirectories = new ArrayList<>();
subDirectories.add(mAssetNames.get(position));
mSelectedAssetPath = Utils.makeFilePath(MISSION_ASSET_FOLDER_NAME, subDirectories);
// Display RunSpecificationSelectionFragment.
Fragment runSpecificationsFragment =
((MainActivity) getActivity()).getGameViews().getRunSpecificationsFragment();
getActivity().getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.remove(this)
.add(R.id.container, runSpecificationsFragment, GameViews.RUN_SPECIFICATIONS_TAG)
.addToBackStack(null)
.commit();
}
public String getSelectedMissionName() {
return mSelectedMissionName;
}
public String getSelectedAssetPath() {
return mSelectedAssetPath;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/MusicSelectionFragment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.gui;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.fpl.gim.examplegame.MainActivity;
import com.google.fpl.gim.examplegame.R;
/**
* A fragment notifying the user to go select music to listen to during their run.
*/
public class MusicSelectionFragment extends Fragment {
private static final String TAG = MusicSelectionFragment.class.getSimpleName();
private Button mReadyButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_music_selection, container, false);
mReadyButton = (Button) rootView.findViewById(R.id.start_mission_button);
mReadyButton.setEnabled(true);
mReadyButton.setText(R.string.start_mission_button);
return rootView;
}
@Override public void onResume() {
super.onResume();
((MainActivity)getActivity()).setActionBarTitle(R.string.select_music_title);
}
public void disableReadyButton() {
mReadyButton.setEnabled(false);
mReadyButton.setText(R.string.start_mission_pressed);
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/NotificationOptions.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.gui;
import android.support.v4.app.NotificationCompat;
import com.google.fpl.gim.examplegame.R;
/**
* Options to build a notification from. Subset of all options that an Android notification may
* have.
*/
public class NotificationOptions {
private int mNotificationId;
private int mSmallIconResourceId;
private String mTitle;
private String mContent;
private NotificationCompat.Action[] mActions = null;
private int mNotificationDefaults;
private int mNotificationPriority;
private long[] mVibratePattern;
private static final int DEFAULT_ID = 1234;
private static final int DEFAULT_SMALL_ICON_RESOURCE_ID = R.drawable.ic_notification;
private static final String DEFAULT_TITLE = "Enemy!";
private static final String DEFAULT_CONTENT = "An enemy appeared, what will you do?";
// Phone notification settings for vibration, sound, and lights.
private static final int APP_NOTIFICATION_DEFAULTS = NotificationCompat.DEFAULT_ALL;
// Maximum priority, so it will be the first notification on the wearable device.
private static final int DEFAULT_PRIORITY = NotificationCompat.PRIORITY_DEFAULT;
/**
* Default constructor.
*/
public NotificationOptions() {
}
/**
* Constructor to set all build options at creation.
*/
public NotificationOptions(int notificationId, int smallIconResourceId, String title,
String content, NotificationCompat.Action[] actions,
int notificationDefaults, int notificationPriority,
long[] vibratePattern) {
this.mNotificationId = notificationId;
this.mSmallIconResourceId = smallIconResourceId;
this.mTitle = title;
this.mContent = content;
this.mActions = actions;
this.mNotificationDefaults = notificationDefaults;
this.mNotificationPriority = notificationPriority;
this.mVibratePattern = vibratePattern;
}
/**
* Statically create default build options.
*
* @return Default build options for a notification.
*/
public static NotificationOptions getDefaultNotificationOptions() {
NotificationOptions options = new NotificationOptions();
options.mNotificationId = DEFAULT_ID;
options.mSmallIconResourceId = DEFAULT_SMALL_ICON_RESOURCE_ID;
options.mTitle = DEFAULT_TITLE;
options.mContent = DEFAULT_CONTENT;
options.mNotificationDefaults = APP_NOTIFICATION_DEFAULTS;
options.mNotificationPriority = DEFAULT_PRIORITY;
return options;
}
/**
* Small icon, title, and text must be set for all notifications.
*
* @param smallIconResourceId The resource Id of a picture to use as the small icon.
* @param title A string to use as the notification title.
* @param content A string to use as the notification content.
*/
public void setRequiredOptions(int smallIconResourceId, String title,
String content) {
this.mSmallIconResourceId = smallIconResourceId;
this.mTitle = title;
this.mContent = content;
}
/**
* Set actions for this notification.
*
* @param actions Actions associated with the notification.
*/
public void setActions(NotificationCompat.Action[] actions) {
this.mActions = actions;
}
/**
* Notification defaults are ringtones, vibration patterns, and LED colors for the notification.
*
* @param notificationDefaults Defaults to use for this notification.
*/
public void setNotificationDefaults(int notificationDefaults) {
this.mNotificationDefaults = notificationDefaults;
}
/**
* Priority determines the notification's position in the notification list.\
* @param notificationPriority Priority to use for this notification.
*/
public void setNotificationPriority(int notificationPriority) {
this.mNotificationPriority = notificationPriority;
}
public void setNotificationId(int id) {
this.mNotificationId = id;
}
public void setPriorityAsDefault() {
mNotificationPriority = NotificationCompat.PRIORITY_DEFAULT;
}
public void setPriorityAsHigh() {
mNotificationPriority = NotificationCompat.PRIORITY_HIGH;
}
public void setPriorityAsMax() {
mNotificationPriority = NotificationCompat.PRIORITY_MAX;
}
public void setContent(String content) {
this.mContent = content;
}
public void setTitle(String title) {
this.mTitle = title;
}
public void setVibratePattern(long[] vibratePattern) { this.mVibratePattern = vibratePattern; }
public int getNotificationPriority() {
return mNotificationPriority;
}
public int getNotificationId() {
return mNotificationId;
}
public int getSmallIconResourceId() {
return mSmallIconResourceId;
}
public String getTitle() {
return mTitle;
}
public String getContent() {
return mContent;
}
public NotificationCompat.Action[] getActions() {
return mActions;
}
public int getNotificationDefaults() {
return mNotificationDefaults;
}
public long[] getVibratePattern() { return mVibratePattern; }
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/RunSpecificationSelectionFragment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.gui;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.fpl.gim.examplegame.MainActivity;
import com.google.fpl.gim.examplegame.R;
/**
* A UI Fragment that represents the game's run specification selection screen.
*/
public class RunSpecificationSelectionFragment extends Fragment {
private static final String TAG = RunSpecificationSelectionFragment.class.getSimpleName();
// The minimum allowed challenge pace.
private static final float CHALLENGE_PACE_MIN_MINUTES_PER_MILE = 8f;
// The maximum allowed challenge pace.
private static final float CHALLENGE_PACE_MAX_MINUTES_PER_MILE = 30f;
// The range of the challenge pace.
private static final float CHALLENGE_PACE_RANGE_MINUTES_PER_MILE =
CHALLENGE_PACE_MAX_MINUTES_PER_MILE - CHALLENGE_PACE_MIN_MINUTES_PER_MILE;
// The default challenge pace.
private static final float CHALLENGE_PACE_DEFAULT_MINUTES_PER_MILE = 20f;
private static final int CHALLENGE_PACE_INCREMENTS_PER_MINUTE = 4;
// The maximum value of the challenge pace seek bar.
private static final int CHALLENGE_PACE_SEEK_BAR_MAX = (int)
CHALLENGE_PACE_RANGE_MINUTES_PER_MILE * CHALLENGE_PACE_INCREMENTS_PER_MINUTE;
// The default value for the progress bar.(int)(
private static final int CHALLENGE_PACE_PROGRESS_BAR_DEFAULT = (int) (
(1.0f -
(CHALLENGE_PACE_DEFAULT_MINUTES_PER_MILE - CHALLENGE_PACE_MIN_MINUTES_PER_MILE)
/ CHALLENGE_PACE_RANGE_MINUTES_PER_MILE) * CHALLENGE_PACE_SEEK_BAR_MAX);
private static final float MISSION_LENGTH_MINUTES = 30.0f;
private static final float INTERVAL_LENGTH_MINUTES = 1.5f;
// SeekBar for selecting a challenge pace.
SeekBar mChallengePaceSeekBar;
// Text display of the current selected challenge pace.
TextView mChallengePaceText;
private float mSelectedMissionLengthMinutes;
private float mSelectedIntervalLengthMinutes;
private float mSelectedChallengePaceMinutesPerMile;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_run_specifications, container, false);
mChallengePaceSeekBar = (SeekBar) rootView.findViewById(R.id.challenge_speed_field);
mChallengePaceSeekBar.setMax(CHALLENGE_PACE_SEEK_BAR_MAX);
mChallengePaceSeekBar.setProgress(CHALLENGE_PACE_PROGRESS_BAR_DEFAULT);
mChallengePaceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
updateChallengePaceText(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mChallengePaceText = (TextView) rootView.findViewById(R.id.challenge_speed_text);
updateChallengePaceText(CHALLENGE_PACE_PROGRESS_BAR_DEFAULT);
return rootView;
}
@Override public void onResume() {
super.onResume();
((MainActivity)getActivity()).setActionBarTitle(R.string.run_specification_title);
}
public void onEnterPressed() {
// Currently does not query the user for a run length. Assume each mission is 30 minutes.
mSelectedMissionLengthMinutes = MISSION_LENGTH_MINUTES;
// Currently does not query the user for an interval length. Assume each interval is 1.5
// minutes.
mSelectedIntervalLengthMinutes = INTERVAL_LENGTH_MINUTES;
mSelectedChallengePaceMinutesPerMile =
calculateChallengePaceFromProgress(mChallengePaceSeekBar.getProgress());
// Display MusicSelectionFragment.
Fragment musicSelectionFragment =
((MainActivity) getActivity()).getGameViews().getMusicSelectionFragment();
getActivity().getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.remove(this)
.add(R.id.container, musicSelectionFragment, GameViews.MUSIC_SELECTION_TAG)
.addToBackStack(null)
.commit();
}
/**
* Displays the currently selected Challenge Pace based on SeekBar progress.
* @param progress Int representing progress from 0 to CHALLENGE_PACE_SEEK_BAR_MAX.
*/
private void updateChallengePaceText(int progress) {
float minutesPerMile = calculateChallengePaceFromProgress(progress);
String formattedText = String.format(getActivity()
.getString(R.string.challenge_speed_display), minutesPerMile);
mChallengePaceText.setText(formattedText);
}
/**
* Calculates Challenge Pace based on SeekBar progress.
* @param progress Int representing progress from 0 to CHALLENGE_PACE_SEEK_BAR_MAX.
* @return A challenge pace in minutes per mile.
*/
private float calculateChallengePaceFromProgress(int progress) {
return CHALLENGE_PACE_MIN_MINUTES_PER_MILE
+ ((1.0f - ((float) progress) / CHALLENGE_PACE_SEEK_BAR_MAX)
* CHALLENGE_PACE_RANGE_MINUTES_PER_MILE);
}
public float getSelectedMissionLengthMinutes() {
return mSelectedMissionLengthMinutes;
}
public float getSelectedIntervalLengthMinutes() {
return mSelectedIntervalLengthMinutes;
}
public float getSelectedChallengePaceMinutesPerMile() {
return mSelectedChallengePaceMinutesPerMile;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/gui/StartMenuFragment.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.gui;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.fpl.gim.examplegame.MainActivity;
import com.google.fpl.gim.examplegame.R;
import com.google.fpl.gim.examplegame.utils.Utils;
/**
* A UI fragment that represents the game's start screen. No data is stored in this fragment.
*/
public class StartMenuFragment extends Fragment {
private static final String TAG = StartMenuFragment.class.getSimpleName();
private Button mStartButton;
private boolean isGoogleFitConnected;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_start, container, false);
mStartButton = (Button) rootView.findViewById(R.id.start_button);
updateStartButton();
return rootView;
}
@Override public void onResume() {
super.onResume();
((MainActivity)getActivity()).setActionBarTitle(R.string.app_name);
}
public void onStartButtonPressed() {
Utils.logDebug(TAG, "onStartButtonPressed");
// Display MissionSelectionFragment
MissionSelectionFragment missionSelectionFragment =
((MainActivity) getActivity()).getGameViews().getListOfMissionsFragment();
getActivity().getFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
.remove(this)
.add(R.id.container, missionSelectionFragment, GameViews.LIST_OF_MISSIONS_TAG)
.addToBackStack(null)
.commit();
}
public void onFitStatusUpdated(boolean connected) {
isGoogleFitConnected = connected;
updateStartButton();
}
private void updateStartButton() {
if (isGoogleFitConnected) {
mStartButton.setEnabled(true);
mStartButton.setText(R.string.start_button_ready);
} else {
mStartButton.setEnabled(false);
mStartButton.setText(R.string.start_button_not_connected);
}
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/utils/MissionParseException.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.utils;
/**
* An exception for problems during the parsing of a mission.
*/
public class MissionParseException extends Exception {
private static final String MOMENT_TYPE_EXCEPTION = "Mission could not be parsed.";
public MissionParseException() {
super(MOMENT_TYPE_EXCEPTION);
}
public MissionParseException(String s) {
super(s);
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/utils/MissionParser.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.utils;
import android.net.Uri;
import com.google.fpl.gim.examplegame.Choice;
import com.google.fpl.gim.examplegame.ChoiceMoment;
import com.google.fpl.gim.examplegame.ChoiceMomentData;
import com.google.fpl.gim.examplegame.Mission;
import com.google.fpl.gim.examplegame.Moment;
import com.google.fpl.gim.examplegame.Outcome;
import com.google.fpl.gim.examplegame.SfxMoment;
import com.google.fpl.gim.examplegame.SfxMomentData;
import com.google.fpl.gim.examplegame.SpokenTextMoment;
import com.google.fpl.gim.examplegame.SpokenTextMomentData;
import com.google.fpl.gim.examplegame.TimerMoment;
import com.google.fpl.gim.examplegame.TimerMomentData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
/**
* A class for parsing a mission in a file.
*/
public class MissionParser {
private static final String TAG = MissionParser.class.getSimpleName();
private static final String ELEMENT_MISSION = "mission";
private static final String MISSION_ATTRIBUTE_START_ID = "start_id";
private static final String MISSION_ATTRIBUTE_NAME = "name";
private static final String ELEMENT_MOMENT = "moment";
// Types of moments.
private static final String MOMENT_TYPE_TIMER = "timer";
private static final String MOMENT_TYPE_SFX = "sfx";
private static final String MOMENT_TYPE_SPOKEN_TEXT = "spoken_text";
private static final String MOMENT_TYPE_CHOICE = "choice";
// Attributes for all moments.
private static final String MOMENT_ATTRIBUTE_TYPE = "type";
private static final String MOMENT_ATTRIBUTE_ID = "id";
// Attributes for specific types of moments.
private static final String ELEMENT_CHOICE = "choice";
private static final String ELEMENT_DESCRIPTION = "description";
private static final String ELEMENT_NEXT_MOMENT = "next_moment";
private static final String NEXT_MOMENT_ATTRIBUTE_ID = "id";
private static final String ELEMENT_LENGTH_MINUTES = "length_minutes";
private static final String ELEMENT_TIMEOUT_LENGTH_MINUTES = "timeout_length_minutes";
private static final String ELEMENT_DEFAULT_CHOICE = "default_choice";
private static final String ELEMENT_URI = "uri";
private static final String DEFAULT_CHOICE_ATTRIBUTE_ID = "id";
private static final String ELEMENT_OUTCOME = "outcome";
private static final String CHOICE_ATTRIBUTE_ID = "id";
private static final String ELEMENT_TEXT_TO_SPEAK = "text_to_speak";
private static final String ELEMENT_FICTIONAL_PROGRESS = "fictional_progress";
private static final String ELEMENT_ICON = "icon";
private static final String ICON_ATTRIBUTE_NAME = "name";
// Attributes for outcomes.
private static final String OUTCOME_ATTRIBUTE_DEPLETE_WEAPON = "deplete_weapon";
private static final String OUTCOME_ATTRIBUTE_INCREMENT_ENEMIES = "increment_enemies";
// ID that signifies the moment whose next is this is an ending moment.
private static final String DEFAULT_END_ID = null;
// ID that signifies that this Choice should only be displayed when the user's weapon is
// charged.
public static final String FIRE_WEAPON_CHOICE_ID = "fire";
/**
* Adds the Moments that define a Mission to that Mission by reading from input. Assumes
* XML file.
* @param missionStream The InputStream to read from.
* @param mission The Mission object to add Moments to.
* @throws MissionParseException
*/
public static void parseMission(InputStream missionStream, Mission mission) throws
MissionParseException {
Document doc = getDocumentFromInputStream(missionStream);
doc.getDocumentElement().normalize();
// Find the Mission's starting Moment.
NodeList missionNodes = doc.getElementsByTagName(ELEMENT_MISSION);
String startId = null;
for (int i = 0; i < missionNodes.getLength(); i++) {
Node missionNode = missionNodes.item(i);
if (isElementNode(missionNode)) {
startId = ((Element) missionNode).getAttribute(MISSION_ATTRIBUTE_START_ID);
Utils.logDebug(TAG, "Start id is \"" + startId + "\".");
break;
}
}
mission.setFirstMomentId(startId);
// Each Moment is represented as an Element
NodeList momentsList = doc.getElementsByTagName(ELEMENT_MOMENT);
for (int i = 0; i < momentsList.getLength(); i++) {
Node momentNode = momentsList.item(i);
// We check to make sure that we have Elements, though getElementsByTagName should
// provide only Elements.
if (isElementNode(momentNode)) {
Moment moment;
Element momentElement = (Element) momentNode;
// Data for all Moments
String id = momentElement.getAttribute(MOMENT_ATTRIBUTE_ID);
String momentType = momentElement.getAttribute(MOMENT_ATTRIBUTE_TYPE);
// Ideally would use Java 7 to switch on the strings themselves, but
// project is not configured to use Java 7.
if (momentType.equals(MOMENT_TYPE_CHOICE)) {
Utils.logDebug(TAG, "Choice moment created.");
ChoiceMomentData momentData = parseChoiceMomentElement(id, momentElement);
moment = new ChoiceMoment(mission, momentData);
} else if (momentType.equals(MOMENT_TYPE_SFX)) {
Utils.logDebug(TAG, "Sfx moment created.");
SfxMomentData momentData = parseSfxMoment(id, momentElement);
moment = new SfxMoment(mission, momentData);
} else if (momentType.equals(MOMENT_TYPE_TIMER)) {
Utils.logDebug(TAG, "Timer moment created.");
TimerMomentData momentData = parseTimerMoment(id, momentElement);
moment = new TimerMoment(mission, momentData);
} else if (momentType.equals(MOMENT_TYPE_SPOKEN_TEXT)) {
Utils.logDebug(TAG, "Spoken text moment created.");
SpokenTextMomentData momentData = parseSpokenTextMoment(id, momentElement);
moment = new SpokenTextMoment(mission, momentData);
} else {
throw new MissionParseException("Moment type invalid.");
}
mission.addMoment(id, moment);
}
}
}
/**
* Everything in an XML document is represented as a Document Object Model Node. Elements are
* defined between opening and closing tags, for example "".
* @param node a DOM Node from a Document
* @return true if the DOM Node is an Element.
*/
private static boolean isElementNode(Node node) {
return node.getNodeType() == Node.ELEMENT_NODE;
}
/**
* Parses an Element representing an SfxMoment to create SfxMomentData.
* @param momentId Already parsed data about the Moment.
* @param momentElement the DOM Element to be parsed.
* @return data to construct an SfxMoment
*/
private static SfxMomentData parseSfxMoment(String momentId, Element momentElement)
throws MissionParseException {
Uri uri = parseUriElement(findSingleChildElementByTag(momentElement, ELEMENT_URI));
String nextMomentId = getNextMomentId(momentElement);
ArrayList fictionalProgress = parseMomentFictionalProgress(momentElement);
return new SfxMomentData(momentId, nextMomentId, fictionalProgress, uri);
}
/**
* Parses an Element representing a TimerMoment to create TimerMomentData.
* @param momentId Already parsed data about the Moment.
* @param momentElement the DOM Element to be parsed.
* @return data to construct a TimerMoment
*/
private static TimerMomentData parseTimerMoment(String momentId, Element momentElement)
throws MissionParseException {
float momentLengthMinutes = parseLengthMinutesElement(
findSingleChildElementByTag(momentElement, ELEMENT_LENGTH_MINUTES));
String nextMomentId = getNextMomentId(momentElement);
ArrayList fictionalProgress = parseMomentFictionalProgress(momentElement);
return new TimerMomentData(momentId, nextMomentId, fictionalProgress, momentLengthMinutes);
}
/**
* Parses an Element representing a SpokenTextMoment to create SpokenTextMomentData.
* @param momentId Already parsed data about the Moment.
* @param momentElement the DOM Element to be parsed.
* @return data to construct an SpokenTextMoment
*/
private static SpokenTextMomentData parseSpokenTextMoment(String momentId,
Element momentElement) throws MissionParseException {
String textToSpeak = parseTextToSpeakElement(
findSingleChildElementByTag(momentElement, ELEMENT_TEXT_TO_SPEAK));
String nextMomentId = getNextMomentId(momentElement);
ArrayList fictionalProgress = parseMomentFictionalProgress(momentElement);
return new SpokenTextMomentData(momentId, nextMomentId, fictionalProgress, textToSpeak);
}
/**
* Parses an Element representing a ChoiceMoment to create ChoiceMomentData.
* @param momentId Already parsed data about the Moment.
* @param momentElement the DOM Element to be parsed.
* @return data to construct an ChoiceMoment
*/
private static ChoiceMomentData parseChoiceMomentElement(String momentId,
Element momentElement) throws MissionParseException {
String description = getDescription(momentElement);
float timeoutLengthMinutes = parseTimeoutLengthMinutesElement(
findSingleChildElementByTag(momentElement, ELEMENT_TIMEOUT_LENGTH_MINUTES));
String defaultChoiceId = parseDefaultChoiceElement(
findSingleChildElementByTag(momentElement, ELEMENT_DEFAULT_CHOICE));
ArrayList fictionalProgress = parseMomentFictionalProgress(momentElement);
ChoiceMomentData data = new ChoiceMomentData(momentId, fictionalProgress, description,
defaultChoiceId, timeoutLengthMinutes);
NodeList choiceNodes = momentElement.getElementsByTagName(ELEMENT_CHOICE);
if (choiceNodes.getLength() > ChoiceMoment.MAXIMUM_NUM_OF_CHOICES) {
throw new MissionParseException("ChoiceMoments can have no more than "
+ ChoiceMoment.MAXIMUM_NUM_OF_CHOICES + " Choices.");
}
if (choiceNodes.getLength() < ChoiceMoment.MINIMUM_NUM_OF_CHOICES) {
throw new MissionParseException("ChoiceMoments can have no fewer than "
+ ChoiceMoment.MINIMUM_NUM_OF_CHOICES + " Choices.");
}
boolean defaultChoiceIsExistingChoice = false;
for (int i = 0; i < choiceNodes.getLength(); i++) {
Node choiceNode = choiceNodes.item(i);
if (isElementNode(choiceNode)) {
Choice choice = parseChoiceElement((Element) choiceNode);
if (choice.getChoiceId() == defaultChoiceId ||
choice.getChoiceId().equals(defaultChoiceId)) {
defaultChoiceIsExistingChoice = true;
}
data.addChoice(choice);
}
}
if (!defaultChoiceIsExistingChoice) {
throw new MissionParseException("Default choice ID is not a valid Choice.");
}
return data;
}
/**
* Creates a Choice from a DOM Element representing a Choice.
* @param choiceElement The DOM element representing a Choice.
* @return a Choice as defined in the DOM Element.
*/
private static Choice parseChoiceElement(Element choiceElement) throws MissionParseException {
String id = choiceElement.getAttribute(CHOICE_ATTRIBUTE_ID);
String description = getDescription(choiceElement);
String nextMomentId = getNextMomentId(choiceElement);
Outcome outcome =
parseOutcomeElement(findSingleChildElementByTag(choiceElement, ELEMENT_OUTCOME));
boolean requiresChargedWeapon = false;
if (id.equals(MissionParser.FIRE_WEAPON_CHOICE_ID)) {
requiresChargedWeapon = true;
}
ArrayList fictionalProgress = parseNestedFictionalProgress(choiceElement);
String iconName =
parseIconElement(findSingleChildElementByTag(choiceElement, ELEMENT_ICON));
return new Choice(id, description, nextMomentId, outcome, requiresChargedWeapon,
fictionalProgress, iconName);
}
/**
* Creates an Outcome from a DOM Element representing an Outcome.
* @param outcomeElement The DOM element representing an Outcome.
* @return an Outcome as defined in the DOM Element.
*/
private static Outcome parseOutcomeElement(Element outcomeElement) {
boolean depleteWeapon =
Boolean.valueOf(outcomeElement.getAttribute(OUTCOME_ATTRIBUTE_DEPLETE_WEAPON));
boolean incrementEnemies =
Boolean.valueOf(outcomeElement.getAttribute(OUTCOME_ATTRIBUTE_INCREMENT_ENEMIES));
return new Outcome(depleteWeapon, incrementEnemies);
}
/**
* Given an XML element that has a nested next_moment element, finds the next moment ID.
* @param element An XML element.
* @return The next moment ID for the element.
*/
private static String getNextMomentId(Element element) throws MissionParseException {
Element nextMomentElement = findSingleChildElementByTag(element, ELEMENT_NEXT_MOMENT);
// If the element does not have a next moment, then set to the default end signifier.
if (nextMomentElement == null) {
return DEFAULT_END_ID;
}
return parseNextMomentElement(nextMomentElement);
}
/**
* Given an XML element that has a nested description element, finds the description.
* @param element An XML element.
* @return The description for the element.
*/
private static String getDescription(Element element) throws MissionParseException {
return parseDescriptionElement(findSingleChildElementByTag(element, ELEMENT_DESCRIPTION));
}
/**
* Finds the first occurrence of a child Element of a given tag within a parent's tree.
* @param parent An Element with child Elements
* @param tag The Element to find
* @return The first occurrence of an Element of type tag within the parent's child tree.
*/
private static Element findSingleChildElementByTag(Element parent, String tag)
throws MissionParseException {
Node node = null;
NodeList nodes = parent.getElementsByTagName(tag);
for (int i = 0; i < nodes.getLength(); i++) {
node = nodes.item(i);
if (isElementNode(node)) {
break;
}
node = null;
}
// All attributes are required except the 'next_moment' attribute. The lack of a
// 'next_moment' attribute signifies that the moment is the last moment in the mission.
if (!tag.equals(ELEMENT_NEXT_MOMENT) && node == null) {
throw new MissionParseException(tag + " could not be found.");
}
return (Element) node;
}
private static String parseNextMomentElement(Element nextMomentElement) {
String nextMomentId = nextMomentElement.getAttribute(NEXT_MOMENT_ATTRIBUTE_ID);
if (nextMomentId == null || nextMomentId.equals("")) {
return DEFAULT_END_ID;
}
return nextMomentId;
}
private static float parseLengthMinutesElement(Element lengthMinutesElement)
throws MissionParseException {
Node node = lengthMinutesElement.getFirstChild();
if (node == null) {
throw new MissionParseException("Length minutes element could not be found.");
}
return Float.parseFloat(node.getTextContent());
}
private static Uri parseUriElement(Element uriElement) throws MissionParseException {
Node node = uriElement.getFirstChild();
if (node == null) {
throw new MissionParseException("URI element could not be found.");
}
return Uri.parse(node.getTextContent());
}
private static String parseTextToSpeakElement(Element textToSpeakElement)
throws MissionParseException {
Node node = textToSpeakElement.getFirstChild();
if (node == null) {
throw new MissionParseException("Text to speak element could not be found.");
}
return node.getTextContent();
}
private static String parseDescriptionElement(Element descriptionElement)
throws MissionParseException {
Node node = descriptionElement.getFirstChild();
if (node == null) {
throw new MissionParseException("Description element could not be found.");
}
return descriptionElement.getTextContent();
}
private static float parseTimeoutLengthMinutesElement(Element timeoutLengthMinutesElement)
throws MissionParseException {
Node node = timeoutLengthMinutesElement.getFirstChild();
if (node == null) {
throw new MissionParseException("Timeout length minutes element could not be found.");
}
return Float.parseFloat(timeoutLengthMinutesElement.getFirstChild().getTextContent());
}
private static String parseDefaultChoiceElement(Element defaultChoiceElement)
throws MissionParseException {
String defaultChoice = defaultChoiceElement.getAttribute(DEFAULT_CHOICE_ATTRIBUTE_ID);
if (defaultChoice == null) {
throw new MissionParseException("Default choice element could not be found.");
}
if (defaultChoice.equals(FIRE_WEAPON_CHOICE_ID)) {
throw new MissionParseException("Default choice cannot be 'fire'.");
}
return defaultChoice;
}
/**
* Determines the name of a mission.
* @param missionStream InputStream to read from.
* @return A string of the name of the mission. Empty string if a name is not specified.
* @throws MissionParseException
*/
public static String getMissionName(InputStream missionStream) throws MissionParseException {
Document doc = getDocumentFromInputStream(missionStream);
doc.getDocumentElement().normalize();
NodeList missionNodes = doc.getElementsByTagName(ELEMENT_MISSION);
String missionName;
for (int i = 0; i < missionNodes.getLength(); i++) {
Node missionNode = missionNodes.item(i);
if (isElementNode(missionNode)) {
// Gives an empty string if the attribute is missing.
missionName = ((Element) missionNode).getAttribute(MISSION_ATTRIBUTE_NAME);
if (missionName.equals("")) {
throw new MissionParseException("Mission name missing.");
}
Utils.logDebug(TAG, "Mission name is " + missionName);
return missionName;
}
}
// No Element Node for Mission.
throw new MissionParseException("Mission element could not be found.");
}
/**
* Creates a Document given an InputStream.
* @param missionStream The stream to open a document from.
* @return The document, successfully parsed from xml.
* @throws MissionParseException
*/
private static Document getDocumentFromInputStream(InputStream missionStream) throws
MissionParseException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
throw new MissionParseException("ParserConfigurationException while reading mission.");
}
Document doc;
try {
doc = builder.parse(missionStream);
} catch (SAXException e) {
e.printStackTrace();
throw new MissionParseException("SAXException while reading mission.");
} catch (IOException e) {
e.printStackTrace();
throw new MissionParseException("IOException while reading mission.");
}
return doc;
}
/**
* Determines the Fictional Progress strings associated with a moment.
* @param momentElement The moment to parse.
* @return A list of Fictional Progress strings.
*/
private static ArrayList parseMomentFictionalProgress(Element momentElement)
throws MissionParseException {
ArrayList progress = new ArrayList<>();
NodeList fictionalProgressNodes =
momentElement.getElementsByTagName(ELEMENT_FICTIONAL_PROGRESS);
for (int i = 0; i < fictionalProgressNodes.getLength(); i++) {
Node node = fictionalProgressNodes.item(i);
Element parent = (Element) node.getParentNode();
if (isElementNode(node) && parent.getTagName().equals(ELEMENT_MOMENT)) {
String progressString = parseFictionalProgressElement((Element) node);
progress.add(progressString);
}
}
return progress;
}
private static String parseFictionalProgressElement(Element element)
throws MissionParseException {
Node node = element.getFirstChild();
if (node == null) {
throw new MissionParseException("Fictional Progress Element not found");
}
String progressString = element.getFirstChild().getTextContent();
if (progressString.equals("")) {
throw new MissionParseException("Fictional Progress empty.");
}
return progressString;
}
private static ArrayList parseNestedFictionalProgress(Element parent)
throws MissionParseException {
ArrayList progressStrings = new ArrayList<>();
NodeList nodeList = parent.getElementsByTagName(ELEMENT_FICTIONAL_PROGRESS);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (isElementNode(node)) {
String progressString = parseFictionalProgressElement((Element) node);
progressStrings.add(progressString);
}
}
return progressStrings;
}
private static String parseIconElement(Element iconElement) throws MissionParseException {
String iconResourceName = iconElement.getAttribute(ICON_ATTRIBUTE_NAME);
if (iconResourceName == null || iconResourceName.equals("")) {
throw new MissionParseException("Icon element has no name attribute.");
}
return iconResourceName;
}
}
================================================
FILE: app/src/main/java/com/google/fpl/gim/examplegame/utils/Utils.java
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.google.fpl.gim.examplegame.utils;
import android.util.Log;
import com.google.fpl.gim.examplegame.BuildConfig;
import java.io.File;
import java.util.ArrayList;
/**
* A few utility functions and classes used by the prototype.
*/
public class Utils {
public static final float SECONDS_TO_NANOS_SCALE = (float) Math.pow(10, 9);
public static final float NANOS_TO_SECONDS_SCALE = (float) Math.pow(10, -9);
public static final int MINUTES_TO_SECONDS_SCALE = 60;
public static final float SECONDS_TO_MINUTES_SCALE = 1.0f / 60;
public static final float MILES_TO_FEET_SCALE = 5280f;
public static final float SECONDS_PER_METER_TO_MINUTES_PER_MILE_SCALE = 26.8224f;
// user control for displaying log messages
private static final boolean DEBUG_LOG = true;
public static float nanosToSeconds(long nanos) {
return nanos / SECONDS_TO_NANOS_SCALE;
}
public static long secondsToNanos(float seconds) {
return (long) (seconds * SECONDS_TO_NANOS_SCALE);
}
public static long minutesToNanos(float min) {
return (long) (min * MINUTES_TO_SECONDS_SCALE * SECONDS_TO_NANOS_SCALE);
}
public static float nanosToMinutes(long nanos) {
return (nanos / SECONDS_TO_NANOS_SCALE / MINUTES_TO_SECONDS_SCALE);
}
public static float feetToMiles(float feet) {
return feet / MILES_TO_FEET_SCALE;
}
public static float secondsToMinutes(float seconds) {
return seconds / MINUTES_TO_SECONDS_SCALE;
}
public static float metersPerSecondToMinutesPerMile(float metersPerSecond) {
if (metersPerSecond == 0.0f) {
return 0.0f;
}
float secondsPerMeter = 1 / metersPerSecond; // seconds per meter
return secondsPerMeter * SECONDS_PER_METER_TO_MINUTES_PER_MILE_SCALE;
}
/**
* Prints debugging messages to the console.
*
* Disabled for non-debug builds.
*
* @param message - The message to print to the console.
*/
public static void logDebug(String tag, String message) {
if (BuildConfig.DEBUG || DEBUG_LOG) {
Log.d(tag, message);
}
}
/**
* Builds a file path.
* @param rootDirectory Highest directory or file name, if not nested.
* @param subDirectories Sub-Directories, or the file name.
* @return A string of the file path.
*/
public static String makeFilePath(String rootDirectory, ArrayList subDirectories) {
File file = new File(rootDirectory);
for (String subDirectory : subDirectories) {
file = new File(file, subDirectory);
}
return file.toString();
}
}
================================================
FILE: app/src/main/res/anim/slide_in_right.xml
================================================
================================================
FILE: app/src/main/res/anim/slide_out_left.xml
================================================
================================================
FILE: app/src/main/res/drawable/weapon_charge_progress.xml
================================================
================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
================================================
FILE: app/src/main/res/layout/end_screen.xml
================================================
================================================
FILE: app/src/main/res/layout/menu_list_item.xml
================================================
================================================
FILE: app/src/main/res/layout/menu_mission_list.xml
================================================
================================================
FILE: app/src/main/res/layout/menu_music_selection.xml
================================================
================================================
FILE: app/src/main/res/layout/menu_run_specifications.xml
================================================
================================================
FILE: app/src/main/res/layout/menu_start.xml
================================================
================================================
FILE: app/src/main/res/layout/placeholder_fragment.xml
================================================
================================================
FILE: app/src/main/res/layout/step_display.xml
================================================
================================================
FILE: app/src/main/res/menu/main.xml
================================================
================================================
FILE: app/src/main/res/values/colors.xml
================================================
#ffebebeb#FFD0D0D0#00933B#ff0d4e
================================================
FILE: app/src/main/res/values/dimens.xml
================================================
16dp16dp10dp10dp20dp20dp40dp50dp100dp175dp120dp10dp10dp70dp40sp25sp15sp20sp350dp
================================================
FILE: app/src/main/res/values/ids.xml
================================================
782016241500CgkI3L6znuEWEAIQAQ
================================================
FILE: app/src/main/res/values/strings.xml
================================================
Games in MotionSettingsExample action clickedEnemyAn enemy appeared! What will you do?ActionEnemy!An enemy appeared, what will you do?Disconnected.
Google client has been disconnected. Please make sure you have WiFi or cellular data
turned on.
Games in Motion
You are in the midst of a zombie apocalypse. Your task is to evade as many zombies as
possible throughout the course of your run.\n\nPlease put on your headphones so you can
receive important instructions. A paired Android wear device is also recommended.
Created by Kate Aplin and Veronica Wharton, Summer 2014 EP Interns
Start!
Connecting to Google Fit…
Select Mission
Select your mission
How long will your mission be?
How long will your intervals be?
Slide to choose your challenge speed.
Choose carefully! Your weapon will only charge when you are running at challenge pace.
\n\nYour mission will last 0 to 60 minutes, with an interval length of 1.5 minutes.
Choose SpeedConfirm Interval Speed
%.2f minutes/mile
Select Music
Select music to play during your run.
Put on your headphones to receive play instructions when the mission starts.\n\nIf you would
like to listen to music as you run, switch to the music app of your choice and play any
track you would like. Return here and select "I am ready!" when you are ready to begin the
mission.
I am ready!Registering sensors...You are currently in a game. Sit tight.You finished a run!Google Fit disconnectedYour progress:Your fitness:Restart---\nmin/mile0%0 steps0:00Challenge pace (min/mile): Number of steps taken: %d;
Number of intervals completed: %d% charged.
Keep running at interval speed to charge your weapon!
minutes per mile.You are not moving.
================================================
FILE: app/src/main/res/values/styles.xml
================================================
================================================
FILE: app/src/main/res/values-w820dp/dimens.xml
================================================
64dp
================================================
FILE: build.gradle
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.
*/
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.0'
}
}
allprojects {
repositories {
mavenCentral()
}
}
================================================
FILE: docs/generate_docs.py
================================================
#!/usr/bin/python
# Copyright 2015 Google Inc. All Rights Reserved.
#
# 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.
"""Generate html documentation from markdown and doxygen comments."""
import os
import sys
THIS_DIR = os.path.realpath(os.path.dirname(__file__))
PROJECT_DIR = os.path.realpath(os.path.join(THIS_DIR, os.pardir))
sys.path.extend(
[os.path.realpath(os.path.join(PROJECT_DIR, os.pardir, os.pardir, '../libs', 'fplutil')),
os.path.realpath(os.path.join(PROJECT_DIR, 'dependencies', 'fplutil'))])
import docs # pylint: disable=C6204
def main():
"""Generate html documentation from markdown and doxygen comments.
Returns:
0 if successful, 1 otherwise.
"""
sys.argv.extend(('--linklint-dir', THIS_DIR,
'--source-dir', os.path.join(THIS_DIR, 'src'),
'--project-dir', PROJECT_DIR))
return docs.generate_docs.main()
if __name__ == '__main__':
sys.exit(main())
================================================
FILE: docs/src/contributing.md
================================================
Contributing {#contributing}
============
Want to contribute? Great! First, read this page (including the small print at
the end).
# Before you contribute
Before we can use your code, you must sign the
[Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual?csw=1)
(CLA), which you can do online. The CLA is necessary mainly because you own the
copyright to your changes, even after your contribution becomes part of our
codebase, so we need your permission to use and distribute your code. We also
need to be sure of various other things—for instance that you'll tell us if you
know that your code infringes on other people's patents. You don't have to sign
the CLA until after you've submitted your code for review and a member has
approved it, but you must do it before we can put your code into our codebase.
Before you start working on a larger contribution, you should get in touch with
us first through the issue tracker with your idea so that we can help out and
possibly guide you. Coordinating up front makes it much easier to avoid
frustration later on.
# Code reviews
All submissions, including submissions by project members, require review. We
use Github pull requests for this purpose.
# The small print
Contributions made by corporations are covered by a different agreement than
the one above, the Software Grant and Corporate Contributor License Agreement.
================================================
FILE: docs/src/doxyfile
================================================
# Doxyfile 1.8.5
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a double hash (##) is considered a comment and is placed in
# front of the TAG it is preceding.
#
# All text after a single hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists, items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (\" \").
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
# This tag specifies the encoding used for all characters in the config file
# that follow. The default is UTF-8 which is also the encoding used for all text
# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
# for the list of possible encodings.
# The default value is: UTF-8.
DOXYFILE_ENCODING = UTF-8
# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
# double-quotes, unless you are using Doxywizard) that should identify the
# project for which the documentation is generated. This name is used in the
# title of most generated pages and in a few other places.
# The default value is: My Project.
PROJECT_NAME = "Games in Motion"
# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER =
# Using the PROJECT_BRIEF tag one can provide an optional one line description
# for a project that appears at the top of each page and should give viewer a
# quick idea about the purpose of the project. Keep the description short.
PROJECT_BRIEF =
# With the PROJECT_LOGO tag one can specify an logo or icon that is included in
# the documentation. The maximum height of the logo should not exceed 55 pixels
# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
# to the output directory.
PROJECT_LOGO = "../../app/src/main/res/mipmap-hdpi/ic_launcher.png"
# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
# into which the generated documentation will be written. If a relative path is
# entered, it will be relative to the location where doxygen was started. If
# left blank the current directory will be used.
OUTPUT_DIRECTORY = "../"
# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
# directories (in 2 levels) under the output directory of each output format and
# will distribute the generated files over these directories. Enabling this
# option can be useful when feeding doxygen a huge amount of source files, where
# putting all generated files in the same directory would otherwise causes
# performance problems for the file system.
# The default value is: NO.
CREATE_SUBDIRS = NO
# The OUTPUT_LANGUAGE tag is used to specify the language in which all
# documentation generated by doxygen is written. Doxygen will use this
# information to generate all constant output in the proper language.
# Possible values are: Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-
# Traditional, Croatian, Czech, Danish, Dutch, English, Esperanto, Farsi,
# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en,
# Korean, Korean-en, Latvian, Norwegian, Macedonian, Persian, Polish,
# Portuguese, Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish,
# Turkish, Ukrainian and Vietnamese.
# The default value is: English.
OUTPUT_LANGUAGE = English
# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
# descriptions after the members that are listed in the file and class
# documentation (similar to Javadoc). Set to NO to disable this.
# The default value is: YES.
BRIEF_MEMBER_DESC = YES
# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
# description of a member or function before the detailed description
#
# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
# brief descriptions will be completely suppressed.
# The default value is: YES.
REPEAT_BRIEF = YES
# This tag implements a quasi-intelligent brief description abbreviator that is
# used to form the text in various listings. Each string in this list, if found
# as the leading text of the brief description, will be stripped from the text
# and the result, after processing the whole list, is used as the annotated
# text. Otherwise, the brief description is used as-is. If left blank, the
# following values are used ($name is automatically replaced with the name of
# the entity):The $name class, The $name widget, The $name file, is, provides,
# specifies, contains, represents, a, an and the.
ABBREVIATE_BRIEF = "The $name class" \
"The $name widget" \
"The $name file" \
is \
provides \
specifies \
contains \
represents \
a \
an \
the
# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
# doxygen will generate a detailed section even if there is only a brief
# description.
# The default value is: NO.
ALWAYS_DETAILED_SEC = NO
# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
# inherited members of a class in the documentation of that class as if those
# members were ordinary class members. Constructors, destructors and assignment
# operators of the base classes will not be shown.
# The default value is: NO.
INLINE_INHERITED_MEMB = NO
# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
# before files name in the file list and in the header files. If set to NO the
# shortest path that makes the file name unique will be used
# The default value is: YES.
FULL_PATH_NAMES = NO
# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
# Stripping is only done if one of the specified strings matches the left-hand
# part of the path. The tag can be used to show relative paths in the file list.
# If left blank the directory from which doxygen is run is used as the path to
# strip.
#
# Note that you can specify absolute paths here, but also relative paths, which
# will be relative from the directory where doxygen is started.
# This tag requires that the tag FULL_PATH_NAMES is set to YES.
STRIP_FROM_PATH =
# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
# path mentioned in the documentation of a class, which tells the reader which
# header file to include in order to use a class. If left blank only the name of
# the header file containing the class definition is used. Otherwise one should
# specify the list of include paths that are normally passed to the compiler
# using the -I flag.
STRIP_FROM_INC_PATH =
# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
# less readable) file names. This can be useful is your file systems doesn't
# support long names like on DOS, Mac, or CD-ROM.
# The default value is: NO.
SHORT_NAMES = NO
# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
# first line (until the first dot) of a Javadoc-style comment as the brief
# description. If set to NO, the Javadoc-style will behave just like regular Qt-
# style comments (thus requiring an explicit @brief command for a brief
# description.)
# The default value is: NO.
JAVADOC_AUTOBRIEF = NO
# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
# line (until the first dot) of a Qt-style comment as the brief description. If
# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
# requiring an explicit \brief command for a brief description.)
# The default value is: NO.
QT_AUTOBRIEF = NO
# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
# a brief description. This used to be the default behavior. The new default is
# to treat a multi-line C++ comment block as a detailed description. Set this
# tag to YES if you prefer the old behavior instead.
#
# Note that setting this tag to YES also means that rational rose comments are
# not recognized any more.
# The default value is: NO.
MULTILINE_CPP_IS_BRIEF = NO
# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
# documentation from any documented member that it re-implements.
# The default value is: YES.
INHERIT_DOCS = YES
# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
# new page for each member. If set to NO, the documentation of a member will be
# part of the file/class/namespace that contains it.
# The default value is: NO.
SEPARATE_MEMBER_PAGES = NO
# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
# uses this value to replace tabs by spaces in code fragments.
# Minimum value: 1, maximum value: 16, default value: 4.
TAB_SIZE = 2
# This tag can be used to specify a number of aliases that act as commands in
# the documentation. An alias has the form:
# name=value
# For example adding
# "sideeffect=@par Side Effects:\n"
# will allow you to put the command \sideeffect (or @sideeffect) in the
# documentation, which will result in a user-defined paragraph with heading
# "Side Effects:". You can put \n's in the value part of an alias to insert
# newlines.
ALIASES =
# This tag can be used to specify a number of word-keyword mappings (TCL only).
# A mapping has the form "name=value". For example adding "class=itcl::class"
# will allow you to use the command class in the itcl::class meaning.
TCL_SUBST =
# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
# only. Doxygen will then generate output that is more tailored for C. For
# instance, some of the names that are used will be different. The list of all
# members will be omitted, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_FOR_C = NO
# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
# Python sources only. Doxygen will then generate output that is more tailored
# for that language. For instance, namespaces will be presented as packages,
# qualified scopes will look different, etc.
# The default value is: NO.
OPTIMIZE_OUTPUT_JAVA = NO
# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
# sources. Doxygen will then generate output that is tailored for Fortran.
# The default value is: NO.
OPTIMIZE_FOR_FORTRAN = NO
# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
# sources. Doxygen will then generate output that is tailored for VHDL.
# The default value is: NO.
OPTIMIZE_OUTPUT_VHDL = NO
# Doxygen selects the parser to use depending on the extension of the files it
# parses. With this tag you can assign which parser to use for a given
# extension. Doxygen has a built-in mapping, but you can override or extend it
# using this tag. The format is ext=language, where ext is a file extension, and
# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
# C#, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL. For instance to make
# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C
# (default is Fortran), use: inc=Fortran f=C.
#
# Note For files without extension you can use no_extension as a placeholder.
#
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen.
EXTENSION_MAPPING =
# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable
# documentation. See http://daringfireball.net/projects/markdown/ for details.
# The output of markdown processing is further processed by doxygen, so you can
# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
# case of backward compatibilities issues.
# The default value is: YES.
MARKDOWN_SUPPORT = YES
# When enabled doxygen tries to link words that correspond to documented
# classes, or namespaces to their corresponding documentation. Such a link can
# be prevented in individual cases by by putting a % sign in front of the word
# or globally by setting AUTOLINK_SUPPORT to NO.
# The default value is: YES.
AUTOLINK_SUPPORT = YES
# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
# to include (a tag file for) the STL sources as input, then you should set this
# tag to YES in order to let doxygen match functions declarations and
# definitions whose arguments contain STL classes (e.g. func(std::string);
# versus func(std::string) {}). This also make the inheritance and collaboration
# diagrams that involve STL classes more complete and accurate.
# The default value is: NO.
BUILTIN_STL_SUPPORT = NO
# If you use Microsoft's C++/CLI language, you should set this option to YES to
# enable parsing support.
# The default value is: NO.
CPP_CLI_SUPPORT = NO
# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
# will parse them like normal C++ but will assume all classes use public instead
# of private inheritance when no explicit protection keyword is present.
# The default value is: NO.
SIP_SUPPORT = NO
# For Microsoft's IDL there are propget and propput attributes to indicate
# getter and setter methods for a property. Setting this option to YES will make
# doxygen to replace the get and set methods by a property in the documentation.
# This will only work if the methods are indeed getting or setting a simple
# type. If this is not the case, or you want to show the methods anyway, you
# should set this option to NO.
# The default value is: YES.
IDL_PROPERTY_SUPPORT = YES
# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
# tag is set to YES, then doxygen will reuse the documentation of the first
# member in the group (if any) for the other members of the group. By default
# all members of a group must be documented explicitly.
# The default value is: NO.
DISTRIBUTE_GROUP_DOC = NO
# Set the SUBGROUPING tag to YES to allow class member groups of the same type
# (for instance a group of public functions) to be put as a subgroup of that
# type (e.g. under the Public Functions section). Set it to NO to prevent
# subgrouping. Alternatively, this can be done per class using the
# \nosubgrouping command.
# The default value is: YES.
SUBGROUPING = YES
# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
# are shown inside the group in which they are included (e.g. using \ingroup)
# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
# and RTF).
#
# Note that this feature does not work in combination with
# SEPARATE_MEMBER_PAGES.
# The default value is: NO.
INLINE_GROUPED_CLASSES = NO
# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
# with only public data fields or simple typedef fields will be shown inline in
# the documentation of the scope in which they are defined (i.e. file,
# namespace, or group documentation), provided this scope is documented. If set
# to NO, structs, classes, and unions are shown on a separate page (for HTML and
# Man pages) or section (for LaTeX and RTF).
# The default value is: NO.
INLINE_SIMPLE_STRUCTS = NO
# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
# enum is documented as struct, union, or enum with the name of the typedef. So
# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
# with name TypeT. When disabled the typedef will appear as a member of a file,
# namespace, or class. And the struct will be named TypeS. This can typically be
# useful for C code in case the coding convention dictates that all compound
# types are typedef'ed and only the typedef is referenced, never the tag name.
# The default value is: NO.
TYPEDEF_HIDES_STRUCT = NO
# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
# cache is used to resolve symbols given their name and scope. Since this can be
# an expensive process and often the same symbol appears multiple times in the
# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
# doxygen will become slower. If the cache is too large, memory is wasted. The
# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
# symbols. At the end of a run doxygen will report the cache usage and suggest
# the optimal cache size from a speed point of view.
# Minimum value: 0, maximum value: 9, default value: 0.
LOOKUP_CACHE_SIZE = 0
#---------------------------------------------------------------------------
# Build related configuration options
#---------------------------------------------------------------------------
# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
# documentation are documented, even if no documentation was available. Private
# class members and static file members will be hidden unless the
# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
# Note: This will also disable the warnings about undocumented members that are
# normally produced when WARNINGS is set to YES.
# The default value is: NO.
EXTRACT_ALL = NO
# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
# be included in the documentation.
# The default value is: NO.
EXTRACT_PRIVATE = NO
# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
# scope will be included in the documentation.
# The default value is: NO.
EXTRACT_PACKAGE = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
# included in the documentation.
# The default value is: NO.
EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
# locally in source files will be included in the documentation. If set to NO
# only classes defined in header files are included. Does not have any effect
# for Java sources.
# The default value is: YES.
EXTRACT_LOCAL_CLASSES = NO
# This flag is only useful for Objective-C code. When set to YES local methods,
# which are defined in the implementation section but not in the interface are
# included in the documentation. If set to NO only methods in the interface are
# included.
# The default value is: NO.
EXTRACT_LOCAL_METHODS = NO
# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base name of
# the file that contains the anonymous namespace. By default anonymous namespace
# are hidden.
# The default value is: NO.
EXTRACT_ANON_NSPACES = NO
# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
# undocumented members inside documented classes or files. If set to NO these
# members will be included in the various overviews, but no documentation
# section is generated. This option has no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy. If set
# to NO these classes will be included in the various overviews. This option has
# no effect if EXTRACT_ALL is enabled.
# The default value is: NO.
HIDE_UNDOC_CLASSES = NO
# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
# (class|struct|union) declarations. If set to NO these declarations will be
# included in the documentation.
# The default value is: NO.
HIDE_FRIEND_COMPOUNDS = NO
# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
# documentation blocks found inside the body of a function. If set to NO these
# blocks will be appended to the function's detailed documentation block.
# The default value is: NO.
HIDE_IN_BODY_DOCS = NO
# The INTERNAL_DOCS tag determines if documentation that is typed after a
# \internal command is included. If the tag is set to NO then the documentation
# will be excluded. Set it to YES to include the internal documentation.
# The default value is: NO.
INTERNAL_DOCS = NO
# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
# names in lower-case letters. If set to YES upper-case letters are also
# allowed. This is useful if you have classes or files whose names only differ
# in case and if your file system supports case sensitive file names. Windows
# and Mac users are advised to set this option to NO.
# The default value is: system dependent.
CASE_SENSE_NAMES = NO
# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
# their full class and namespace scopes in the documentation. If set to YES the
# scope will be hidden.
# The default value is: NO.
HIDE_SCOPE_NAMES = NO
# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
# the files that are included by a file in the documentation of that file.
# The default value is: YES.
SHOW_INCLUDE_FILES = YES
# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
# files with double quotes in the documentation rather than with sharp brackets.
# The default value is: NO.
FORCE_LOCAL_INCLUDES = NO
# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
# documentation for inline members.
# The default value is: YES.
INLINE_INFO = YES
# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
# (detailed) documentation of file and class members alphabetically by member
# name. If set to NO the members will appear in declaration order.
# The default value is: YES.
SORT_MEMBER_DOCS = YES
# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
# descriptions of file, namespace and class members alphabetically by member
# name. If set to NO the members will appear in declaration order.
# The default value is: NO.
SORT_BRIEF_DOCS = NO
# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
# (brief and detailed) documentation of class members so that constructors and
# destructors are listed first. If set to NO the constructors will appear in the
# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
# member documentation.
# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
# detailed member documentation.
# The default value is: NO.
SORT_MEMBERS_CTORS_1ST = NO
# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
# of group names into alphabetical order. If set to NO the group names will
# appear in their defined order.
# The default value is: NO.
SORT_GROUP_NAMES = NO
# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
# fully-qualified names, including namespaces. If set to NO, the class list will
# be sorted only by class name, not including the namespace part.
# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
# Note: This option applies only to the class list, not to the alphabetical
# list.
# The default value is: NO.
SORT_BY_SCOPE_NAME = NO
# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
# type resolution of all parameters of a function it will reject a match between
# the prototype and the implementation of a member function even if there is
# only one candidate or it is obvious which candidate to choose by doing a
# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
# accept a match between prototype and implementation in such cases.
# The default value is: NO.
STRICT_PROTO_MATCHING = NO
# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
# todo list. This list is created by putting \todo commands in the
# documentation.
# The default value is: YES.
GENERATE_TODOLIST = NO
# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
# test list. This list is created by putting \test commands in the
# documentation.
# The default value is: YES.
GENERATE_TESTLIST = NO
# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
# list. This list is created by putting \bug commands in the documentation.
# The default value is: YES.
GENERATE_BUGLIST = NO
# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
# the deprecated list. This list is created by putting \deprecated commands in
# the documentation.
# The default value is: YES.
GENERATE_DEPRECATEDLIST= YES
# The ENABLED_SECTIONS tag can be used to enable conditional documentation
# sections, marked by \if ... \endif and \cond
# ... \endcond blocks.
ENABLED_SECTIONS =
# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
# initial value of a variable or macro / define can have for it to appear in the
# documentation. If the initializer consists of more lines than specified here
# it will be hidden. Use a value of 0 to hide initializers completely. The
# appearance of the value of individual variables and macros / defines can be
# controlled using \showinitializer or \hideinitializer command in the
# documentation regardless of this setting.
# Minimum value: 0, maximum value: 10000, default value: 30.
MAX_INITIALIZER_LINES = 30
# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
# the bottom of the documentation of classes and structs. If set to YES the list
# will mention the files that were used to generate the documentation.
# The default value is: YES.
SHOW_USED_FILES = YES
# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
# will remove the Files entry from the Quick Index and from the Folder Tree View
# (if specified).
# The default value is: YES.
SHOW_FILES = YES
# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
# page. This will remove the Namespaces entry from the Quick Index and from the
# Folder Tree View (if specified).
# The default value is: YES.
SHOW_NAMESPACES = YES
# The FILE_VERSION_FILTER tag can be used to specify a program or script that
# doxygen should invoke to get the current version for each file (typically from
# the version control system). Doxygen will invoke the program by executing (via
# popen()) the command command input-file, where command is the value of the
# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
# by doxygen. Whatever the program writes to standard output is used as the file
# version. For an example see the documentation.
FILE_VERSION_FILTER =
# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
# by doxygen. The layout file controls the global structure of the generated
# output files in an output format independent way. To create the layout file
# that represents doxygen's defaults, run doxygen with the -l option. You can
# optionally specify a file name after the option, if omitted DoxygenLayout.xml
# will be used as the name of the layout file.
#
# Note that if you run doxygen from a directory containing a file called
# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
# tag is left empty.
LAYOUT_FILE = doxygen_layout.xml
# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
# the reference definitions. This must be a list of .bib files. The .bib
# extension is automatically appended if omitted. This requires the bibtex tool
# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
# For LaTeX the style of the bibliography can be controlled using
# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
# search path. Do not use file names with spaces, bibtex cannot handle them. See
# also \cite for info how to create references.
CITE_BIB_FILES =
#---------------------------------------------------------------------------
# Configuration options related to warning and progress messages
#---------------------------------------------------------------------------
# The QUIET tag can be used to turn on/off the messages that are generated to
# standard output by doxygen. If QUIET is set to YES this implies that the
# messages are off.
# The default value is: NO.
QUIET = NO
# The WARNINGS tag can be used to turn on/off the warning messages that are
# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
# this implies that the warnings are on.
#
# Tip: Turn warnings on while writing the documentation.
# The default value is: YES.
WARNINGS = YES
# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
# will automatically be disabled.
# The default value is: YES.
WARN_IF_UNDOCUMENTED = YES
# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
# potential errors in the documentation, such as not documenting some parameters
# in a documented function, or documenting parameters that don't exist or using
# markup commands wrongly.
# The default value is: YES.
WARN_IF_DOC_ERROR = YES
# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
# are documented, but have no documentation for their parameters or return
# value. If set to NO doxygen will only warn about wrong or incomplete parameter
# documentation, but not about the absence of documentation.
# The default value is: NO.
WARN_NO_PARAMDOC = NO
# The WARN_FORMAT tag determines the format of the warning messages that doxygen
# can produce. The string should contain the $file, $line, and $text tags, which
# will be replaced by the file and line number from which the warning originated
# and the warning text. Optionally the format may contain $version, which will
# be replaced by the version of the file (if it could be obtained via
# FILE_VERSION_FILTER)
# The default value is: $file:$line: $text.
WARN_FORMAT = "$file:$line: $text"
# The WARN_LOGFILE tag can be used to specify a file to which warning and error
# messages should be written. If left blank the output is written to standard
# error (stderr).
WARN_LOGFILE =
#---------------------------------------------------------------------------
# Configuration options related to the input files
#---------------------------------------------------------------------------
# The INPUT tag is used to specify the files and/or directories that contain
# documented source files. You may enter file names like myfile.cpp or
# directories like /usr/src/myproject. Separate the files or directories with
# spaces.
# Note: If this tag is empty the current directory is searched.
INPUT = "contributing.md" \
"index.md" \
"programmers_guide/assets.md" \
"programmers_guide/audio.md" \
"programmers_guide/building.md" \
"programmers_guide/core.md" \
"programmers_guide/gameplay.md" \
"programmers_guide/google_api.md" \
"programmers_guide/mission.md" \
"programmers_guide/overview.md" \
"../../readme.md" \
"../../src"
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
# documentation (see: http://www.gnu.org/software/libiconv) for the list of
# possible encodings.
# The default value is: UTF-8.
INPUT_ENCODING = UTF-8
# If the value of the INPUT tag contains directories, you can use the
# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank the
# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
# *.qsf, *.as and *.js.
FILE_PATTERNS = *.c \
*.cc \
*.cxx \
*.cpp \
*.c++ \
*.java \
*.ii \
*.ixx \
*.ipp \
*.i++ \
*.inl \
*.idl \
*.ddl \
*.odl \
*.h \
*.hh \
*.hxx \
*.hpp \
*.h++ \
*.cs \
*.d \
*.php \
*.php4 \
*.php5 \
*.phtml \
*.inc \
*.m \
*.markdown \
*.md \
*.mm \
*.dox \
*.py \
*.f90 \
*.f \
*.for \
*.tcl \
*.vhd \
*.vhdl \
*.ucf \
*.qsf \
*.as \
*.js
# The RECURSIVE tag can be used to specify whether or not subdirectories should
# be searched for input files as well.
# The default value is: NO.
RECURSIVE = YES
# The EXCLUDE tag can be used to specify files and/or directories that should be
# excluded from the INPUT source files. This way you can easily exclude a
# subdirectory from a directory tree whose root is specified with the INPUT tag.
#
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE =
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
# from the input.
# The default value is: NO.
EXCLUDE_SYMLINKS = NO
# If the value of the INPUT tag contains directories, you can use the
# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
# certain files from those directories.
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories for example use the pattern */test/*
EXCLUDE_PATTERNS =
# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
# (namespaces, classes, functions, etc.) that should be excluded from the
# output. The symbol name can be a fully qualified name, a word, or if the
# wildcard * is used, a substring. Examples: ANamespace, AClass,
# AClass::ANamespace, ANamespace::*Test
#
# Note that the wildcards are matched against the file with absolute path, so to
# exclude all test directories use the pattern */test/*
EXCLUDE_SYMBOLS =
# The EXAMPLE_PATH tag can be used to specify one or more files or directories
# that contain example code fragments that are included (see the \include
# command).
EXAMPLE_PATH =
# If the value of the EXAMPLE_PATH tag contains directories, you can use the
# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
# *.h) to filter out the source-files in the directories. If left blank all
# files are included.
EXAMPLE_PATTERNS =
# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
# searched for input files to be used with the \include or \dontinclude commands
# irrespective of the value of the RECURSIVE tag.
# The default value is: NO.
EXAMPLE_RECURSIVE = NO
# The IMAGE_PATH tag can be used to specify one or more files or directories
# that contain images that are to be included in the documentation (see the
# \image command).
IMAGE_PATH =
# The INPUT_FILTER tag can be used to specify a program that doxygen should
# invoke to filter for each input file. Doxygen will invoke the filter program
# by executing (via popen()) the command:
#
#
#
# where is the value of the INPUT_FILTER tag, and is the
# name of an input file. Doxygen will then use the output that the filter
# program writes to standard output. If FILTER_PATTERNS is specified, this tag
# will be ignored.
#
# Note that the filter must not add or remove lines; it is applied before the
# code is scanned, but not when the output code is generated. If lines are added
# or removed, the anchors will not be placed correctly.
INPUT_FILTER =
# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
# basis. Doxygen will compare the file name with each pattern and apply the
# filter if there is a match. The filters are a list of the form: pattern=filter
# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
# patterns match the file name, INPUT_FILTER is applied.
FILTER_PATTERNS =
# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
# INPUT_FILTER ) will also be used to filter the input files that are used for
# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
# The default value is: NO.
FILTER_SOURCE_FILES = NO
# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
# it is also possible to disable source filtering for a specific pattern using
# *.ext= (so without naming a filter).
# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
FILTER_SOURCE_PATTERNS =
# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
# is part of the input, its contents will be placed on the main page
# (index.html). This can be useful if you have a project on for instance GitHub
# and want to reuse the introduction page also for the doxygen output.
USE_MDFILE_AS_MAINPAGE = index.md
#---------------------------------------------------------------------------
# Configuration options related to source browsing
#---------------------------------------------------------------------------
# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
# generated. Documented entities will be cross-referenced with these sources.
#
# Note: To get rid of all source code in the generated output, make sure that
# also VERBATIM_HEADERS is set to NO.
# The default value is: NO.
SOURCE_BROWSER = NO
# Setting the INLINE_SOURCES tag to YES will include the body of functions,
# classes and enums directly into the documentation.
# The default value is: NO.
INLINE_SOURCES = NO
# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
# special comment blocks from generated source code fragments. Normal C, C++ and
# Fortran comments will always remain visible.
# The default value is: YES.
STRIP_CODE_COMMENTS = NO
# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
# function all documented functions referencing it will be listed.
# The default value is: NO.
REFERENCED_BY_RELATION = NO
# If the REFERENCES_RELATION tag is set to YES then for each documented function
# all documented entities called/used by that function will be listed.
# The default value is: NO.
REFERENCES_RELATION = NO
# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
# link to the documentation.
# The default value is: YES.
REFERENCES_LINK_SOURCE = YES
# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
# source code will show a tooltip with additional information such as prototype,
# brief description and links to the definition and documentation. Since this
# will make the HTML file larger and loading of large files a bit slower, you
# can opt to disable this feature.
# The default value is: YES.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
SOURCE_TOOLTIPS = YES
# If the USE_HTAGS tag is set to YES then the references to source code will
# point to the HTML generated by the htags(1) tool instead of doxygen built-in
# source browser. The htags tool is part of GNU's global source tagging system
# (see http://www.gnu.org/software/global/global.html). You will need version
# 4.8.6 or higher.
#
# To use it do the following:
# - Install the latest version of global
# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
# - Make sure the INPUT points to the root of the source tree
# - Run doxygen as normal
#
# Doxygen will invoke htags (and that will in turn invoke gtags), so these
# tools must be available from the command line (i.e. in the search path).
#
# The result: instead of the source browser generated by doxygen, the links to
# source code will now point to the output of htags.
# The default value is: NO.
# This tag requires that the tag SOURCE_BROWSER is set to YES.
USE_HTAGS = NO
# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
# verbatim copy of the header file for each class for which an include is
# specified. Set to NO to disable this.
# See also: Section \class.
# The default value is: YES.
VERBATIM_HEADERS = YES
#---------------------------------------------------------------------------
# Configuration options related to the alphabetical class index
#---------------------------------------------------------------------------
# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
# compounds will be generated. Enable this if the project contains a lot of
# classes, structs, unions or interfaces.
# The default value is: YES.
ALPHABETICAL_INDEX = YES
# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
# which the alphabetical index list will be split.
# Minimum value: 1, maximum value: 20, default value: 5.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
COLS_IN_ALPHA_INDEX = 5
# In case all classes in a project start with a common prefix, all classes will
# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
# can be used to specify a prefix (or a list of prefixes) that should be ignored
# while generating the index headers.
# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
IGNORE_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the HTML output
#---------------------------------------------------------------------------
# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
# The default value is: YES.
GENERATE_HTML = YES
# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_OUTPUT = html
# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
# generated HTML page (for example: .htm, .php, .asp).
# The default value is: .html.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FILE_EXTENSION = .html
# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
# each generated HTML page. If the tag is left blank doxygen will generate a
# standard header.
#
# To get valid HTML the header file that includes any scripts and style sheets
# that doxygen needs, which is dependent on the configuration options used (e.g.
# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
# default header using
# doxygen -w html new_header.html new_footer.html new_stylesheet.css
# YourConfigFile
# and then modify the file new_header.html. See also section "Doxygen usage"
# for information on how to generate the default header that doxygen normally
# uses.
# Note: The header is subject to change so you typically have to regenerate the
# default header when upgrading to a newer version of doxygen. For a description
# of the possible markers and block names see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_HEADER =
# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
# generated HTML page. If the tag is left blank doxygen will generate a standard
# footer. See HTML_HEADER for more information on how to generate a default
# footer and what special commands can be used inside the footer. See also
# section "Doxygen usage" for information on how to generate the default footer
# that doxygen normally uses.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_FOOTER =
# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
# sheet that is used by each HTML page. It can be used to fine-tune the look of
# the HTML output. If left blank doxygen will generate a default style sheet.
# See also section "Doxygen usage" for information on how to generate the style
# sheet that doxygen normally uses.
# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
# it is more robust and this tag (HTML_STYLESHEET) will in the future become
# obsolete.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_STYLESHEET =
# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional user-
# defined cascading style sheet that is included after the standard style sheets
# created by doxygen. Using this option one can overrule certain style aspects.
# This is preferred over using HTML_STYLESHEET since it does not replace the
# standard style sheet and is therefor more robust against future updates.
# Doxygen will copy the style sheet file to the output directory. For an example
# see the documentation.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_STYLESHEET =
# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the HTML output directory. Note
# that these files will be copied to the base HTML output directory. Use the
# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
# files will be copied as-is; there are no commands or markers available.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_EXTRA_FILES = "programmers_guide/change_config.png"
# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
# will adjust the colors in the stylesheet and background images according to
# this color. Hue is specified as an angle on a colorwheel, see
# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
# purple, and 360 is red again.
# Minimum value: 0, maximum value: 359, default value: 220.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_HUE = 220
# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
# in the HTML output. For a value of 0 the output will use grayscales only. A
# value of 255 will produce the most vivid colors.
# Minimum value: 0, maximum value: 255, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_SAT = 100
# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
# luminance component of the colors in the HTML output. Values below 100
# gradually make the output lighter, whereas values above 100 make the output
# darker. The value divided by 100 is the actual gamma applied, so 80 represents
# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
# change the gamma.
# Minimum value: 40, maximum value: 240, default value: 80.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_COLORSTYLE_GAMMA = 80
# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
# page will contain the date and time when the page was generated. Setting this
# to NO can help when comparing the output of multiple runs.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_TIMESTAMP = YES
# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
# documentation will contain sections that can be hidden and shown after the
# page has loaded.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_DYNAMIC_SECTIONS = NO
# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
# shown in the various tree structured indices initially; the user can expand
# and collapse entries dynamically later on. Doxygen will expand the tree to
# such a level that at most the specified number of entries are visible (unless
# a fully collapsed tree already exceeds this amount). So setting the number of
# entries 1 will produce a full collapsed tree by default. 0 is a special value
# representing an infinite number of entries and will result in a full expanded
# tree by default.
# Minimum value: 0, maximum value: 9999, default value: 100.
# This tag requires that the tag GENERATE_HTML is set to YES.
HTML_INDEX_NUM_ENTRIES = 100
# If the GENERATE_DOCSET tag is set to YES, additional index files will be
# generated that can be used as input for Apple's Xcode 3 integrated development
# environment (see: http://developer.apple.com/tools/xcode/), introduced with
# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
# Makefile in the HTML output directory. Running make will produce the docset in
# that directory and running make install will install the docset in
# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
# for more information.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_DOCSET = NO
# This tag determines the name of the docset feed. A documentation feed provides
# an umbrella under which multiple documentation sets from a single provider
# (such as a company or product suite) can be grouped.
# The default value is: Doxygen generated docs.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_FEEDNAME = "Doxygen generated docs"
# This tag specifies a string that should uniquely identify the documentation
# set bundle. This should be a reverse domain-name style string, e.g.
# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_BUNDLE_ID = org.doxygen.Project
# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
# the documentation publisher. This should be a reverse domain-name style
# string, e.g. com.mycompany.MyDocSet.documentation.
# The default value is: org.doxygen.Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_ID = org.doxygen.Publisher
# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
# The default value is: Publisher.
# This tag requires that the tag GENERATE_DOCSET is set to YES.
DOCSET_PUBLISHER_NAME = Publisher
# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
# Windows.
#
# The HTML Help Workshop contains a compiler that can convert all HTML output
# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
# files are now used as the Windows 98 help format, and will replace the old
# Windows help format (.hlp) on all Windows platforms in the future. Compressed
# HTML files also contain an index, a table of contents, and you can search for
# words in the documentation. The HTML workshop also contains a viewer for
# compressed HTML files.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_HTMLHELP = NO
# The CHM_FILE tag can be used to specify the file name of the resulting .chm
# file. You can add a path in front of the file if the result should not be
# written to the html output directory.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_FILE =
# The HHC_LOCATION tag can be used to specify the location (absolute path
# including file name) of the HTML help compiler ( hhc.exe). If non-empty
# doxygen will try to run the HTML help compiler on the generated index.hhp.
# The file has to be specified with full path.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
HHC_LOCATION =
# The GENERATE_CHI flag controls if a separate .chi index file is generated (
# YES) or that it should be included in the master .chm file ( NO).
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
GENERATE_CHI = NO
# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
# and project file content.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
CHM_INDEX_ENCODING =
# The BINARY_TOC flag controls whether a binary table of contents is generated (
# YES) or a normal table of contents ( NO) in the .chm file.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
BINARY_TOC = NO
# The TOC_EXPAND flag can be set to YES to add extra items for group members to
# the table of contents of the HTML help documentation and to the tree view.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
TOC_EXPAND = NO
# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
# (.qch) of the generated HTML documentation.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_QHP = NO
# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
# the file name of the resulting .qch file. The path specified is relative to
# the HTML output folder.
# This tag requires that the tag GENERATE_QHP is set to YES.
QCH_FILE =
# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
# Project output. For more information please see Qt Help Project / Namespace
# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_NAMESPACE = org.doxygen.Project
# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
# Help Project output. For more information please see Qt Help Project / Virtual
# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
# folders).
# The default value is: doc.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_VIRTUAL_FOLDER = doc
# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
# filter to add. For more information please see Qt Help Project / Custom
# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
# filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_NAME =
# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
# custom filter to add. For more information please see Qt Help Project / Custom
# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
# filters).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_CUST_FILTER_ATTRS =
# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
# project's filter section matches. Qt Help Project / Filter Attributes (see:
# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
# This tag requires that the tag GENERATE_QHP is set to YES.
QHP_SECT_FILTER_ATTRS =
# The QHG_LOCATION tag can be used to specify the location of Qt's
# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
# generated .qhp file.
# This tag requires that the tag GENERATE_QHP is set to YES.
QHG_LOCATION =
# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
# generated, together with the HTML files, they form an Eclipse help plugin. To
# install this plugin and make it available under the help contents menu in
# Eclipse, the contents of the directory containing the HTML and XML files needs
# to be copied into the plugins directory of eclipse. The name of the directory
# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
# After copying Eclipse needs to be restarted before the help appears.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_ECLIPSEHELP = NO
# A unique identifier for the Eclipse help plugin. When installing the plugin
# the directory name containing the HTML and XML files should also have this
# name. Each documentation set should have its own identifier.
# The default value is: org.doxygen.Project.
# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
ECLIPSE_DOC_ID = org.doxygen.Project
# If you want full control over the layout of the generated HTML pages it might
# be necessary to disable the index and replace it with your own. The
# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
# of each HTML page. A value of NO enables the index and the value YES disables
# it. Since the tabs in the index contain the same information as the navigation
# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
DISABLE_INDEX = NO
# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
# structure should be generated to display hierarchical information. If the tag
# value is set to YES, a side panel will be generated containing a tree-like
# index structure (just like the one that is generated for HTML Help). For this
# to work a browser that supports JavaScript, DHTML, CSS and frames is required
# (i.e. any modern browser). Windows users are probably better off using the
# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
# further fine-tune the look of the index. As an example, the default style
# sheet generated by doxygen has an example that shows how to put an image at
# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
# the same information as the tab index, you could consider setting
# DISABLE_INDEX to YES when enabling this option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
GENERATE_TREEVIEW = YES
# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
# doxygen will group on one line in the generated HTML documentation.
#
# Note that a value of 0 will completely suppress the enum values from appearing
# in the overview section.
# Minimum value: 0, maximum value: 20, default value: 4.
# This tag requires that the tag GENERATE_HTML is set to YES.
ENUM_VALUES_PER_LINE = 4
# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
# to set the initial width (in pixels) of the frame in which the tree is shown.
# Minimum value: 0, maximum value: 1500, default value: 250.
# This tag requires that the tag GENERATE_HTML is set to YES.
TREEVIEW_WIDTH = 250
# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
# external symbols imported via tag files in a separate window.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
EXT_LINKS_IN_WINDOW = NO
# Use this tag to change the font size of LaTeX formulas included as images in
# the HTML documentation. When you change the font size after a successful
# doxygen run you need to manually remove any form_*.png images from the HTML
# output directory to force them to be regenerated.
# Minimum value: 8, maximum value: 50, default value: 10.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_FONTSIZE = 10
# Use the FORMULA_TRANPARENT tag to determine whether or not the images
# generated for formulas are transparent PNGs. Transparent PNGs are not
# supported properly for IE 6.0, but are supported on all modern browsers.
#
# Note that when changing this option you need to delete any form_*.png files in
# the HTML output directory before the changes have effect.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
FORMULA_TRANSPARENT = YES
# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
# http://www.mathjax.org) which uses client side Javascript for the rendering
# instead of using prerendered bitmaps. Use this if you do not have LaTeX
# installed or if you want to formulas look prettier in the HTML output. When
# enabled you may also need to install MathJax separately and configure the path
# to it using the MATHJAX_RELPATH option.
# The default value is: NO.
# This tag requires that the tag GENERATE_HTML is set to YES.
USE_MATHJAX = NO
# When MathJax is enabled you can set the default output format to be used for
# the MathJax output. See the MathJax site (see:
# http://docs.mathjax.org/en/latest/output.html) for more details.
# Possible values are: HTML-CSS (which is slower, but has the best
# compatibility), NativeMML (i.e. MathML) and SVG.
# The default value is: HTML-CSS.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_FORMAT = HTML-CSS
# When MathJax is enabled you need to specify the location relative to the HTML
# output directory using the MATHJAX_RELPATH option. The destination directory
# should contain the MathJax.js script. For instance, if the mathjax directory
# is located at the same level as the HTML output directory, then
# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
# Content Delivery Network so you can quickly see the result without installing
# MathJax. However, it is strongly recommended to install a local copy of
# MathJax from http://www.mathjax.org before deployment.
# The default value is: http://cdn.mathjax.org/mathjax/latest.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest
# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
# extension names that should be enabled during MathJax rendering. For example
# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_EXTENSIONS =
# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
# of code that will be used on startup of the MathJax code. See the MathJax site
# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
# example see the documentation.
# This tag requires that the tag USE_MATHJAX is set to YES.
MATHJAX_CODEFILE =
# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
# the HTML output. The underlying search engine uses javascript and DHTML and
# should work on any modern browser. Note that when using HTML help
# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
# there is already a search function so this one should typically be disabled.
# For large projects the javascript based search engine can be slow, then
# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
# search using the keyboard; to jump to the search box use + S
# (what the is depends on the OS and browser, but it is typically
# , /
, or both). Inside the search box use the to jump into the search results window, the results can be navigated
# using the . Press to select an item or to cancel
# the search. The filter options can be selected when the cursor is inside the
# search box by pressing +. Also here use the
# to select a filter and or to activate or cancel the filter
# option.
# The default value is: YES.
# This tag requires that the tag GENERATE_HTML is set to YES.
SEARCHENGINE = YES
# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
# implemented using a web server instead of a web client using Javascript. There
# are two flavours of web server based searching depending on the
# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for
# searching and an index file used by the script. When EXTERNAL_SEARCH is
# enabled the indexing and searching needs to be provided by external tools. See
# the section "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
SERVER_BASED_SEARCH = NO
# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
# script for searching. Instead the search results are written to an XML file
# which needs to be processed by an external indexer. Doxygen will invoke an
# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
# search results.
#
# Doxygen ships with an example indexer ( doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see: http://xapian.org/).
#
# See the section "External Indexing and Searching" for details.
# The default value is: NO.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH = NO
# The SEARCHENGINE_URL should point to a search engine hosted by a web server
# which will return the search results when EXTERNAL_SEARCH is enabled.
#
# Doxygen ships with an example indexer ( doxyindexer) and search engine
# (doxysearch.cgi) which are based on the open source search engine library
# Xapian (see: http://xapian.org/). See the section "External Indexing and
# Searching" for details.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHENGINE_URL =
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
# search data is written to a file for indexing by an external tool. With the
# SEARCHDATA_FILE tag the name of this file can be specified.
# The default file is: searchdata.xml.
# This tag requires that the tag SEARCHENGINE is set to YES.
SEARCHDATA_FILE = searchdata.xml
# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
# projects and redirect the results back to the right project.
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTERNAL_SEARCH_ID =
# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
# projects other than the one defined by this configuration file, but that are
# all added to the same external search index. Each project needs to have a
# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
# to a relative location where the documentation can be found. The format is:
# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
# This tag requires that the tag SEARCHENGINE is set to YES.
EXTRA_SEARCH_MAPPINGS =
#---------------------------------------------------------------------------
# Configuration options related to the LaTeX output
#---------------------------------------------------------------------------
# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.
# The default value is: YES.
GENERATE_LATEX = NO
# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_OUTPUT = latex
# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
# invoked.
#
# Note that when enabling USE_PDFLATEX this option is only used for generating
# bitmaps for formulas in the HTML output, but not in the Makefile that is
# written to the output directory.
# The default file is: latex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_CMD_NAME = latex
# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
# index for LaTeX.
# The default file is: makeindex.
# This tag requires that the tag GENERATE_LATEX is set to YES.
MAKEINDEX_CMD_NAME = makeindex
# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
COMPACT_LATEX = NO
# The PAPER_TYPE tag can be used to set the paper type that is used by the
# printer.
# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
# 14 inches) and executive (7.25 x 10.5 inches).
# The default value is: a4.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PAPER_TYPE = a4
# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
# that should be included in the LaTeX output. To get the times font for
# instance you can specify
# EXTRA_PACKAGES=times
# If left blank no extra packages will be included.
# This tag requires that the tag GENERATE_LATEX is set to YES.
EXTRA_PACKAGES =
# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
# generated LaTeX document. The header should contain everything until the first
# chapter. If it is left blank doxygen will generate a standard header. See
# section "Doxygen usage" for information on how to let doxygen write the
# default header to a separate file.
#
# Note: Only use a user-defined header if you know what you are doing! The
# following commands have a special meaning inside the header: $title,
# $datetime, $date, $doxygenversion, $projectname, $projectnumber. Doxygen will
# replace them by respectively the title of the page, the current date and time,
# only the current date, the version number of doxygen, the project name (see
# PROJECT_NAME), or the project number (see PROJECT_NUMBER).
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HEADER =
# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
# generated LaTeX document. The footer should contain everything after the last
# chapter. If it is left blank doxygen will generate a standard footer.
#
# Note: Only use a user-defined footer if you know what you are doing!
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_FOOTER =
# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
# other source files which should be copied to the LATEX_OUTPUT output
# directory. Note that the files will be copied as-is; there are no commands or
# markers available.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_EXTRA_FILES =
# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
# contain links (just like the HTML output) instead of page references. This
# makes the output suitable for online browsing using a PDF viewer.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
PDF_HYPERLINKS = YES
# If the LATEX_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
# the PDF file directly from the LaTeX files. Set this option to YES to get a
# higher quality PDF documentation.
# The default value is: YES.
# This tag requires that the tag GENERATE_LATEX is set to YES.
USE_PDFLATEX = YES
# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
# command to the generated LaTeX files. This will instruct LaTeX to keep running
# if errors occur, instead of asking the user for help. This option is also used
# when generating formulas in HTML.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BATCHMODE = NO
# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
# index chapters (such as File Index, Compound Index, etc.) in the output.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_HIDE_INDICES = NO
# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
# code with syntax highlighting in the LaTeX output.
#
# Note that which sources are shown also depends on other settings such as
# SOURCE_BROWSER.
# The default value is: NO.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_SOURCE_CODE = NO
# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
# bibliography, e.g. plainnat, or ieeetr. See
# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
# The default value is: plain.
# This tag requires that the tag GENERATE_LATEX is set to YES.
LATEX_BIB_STYLE = plain
#---------------------------------------------------------------------------
# Configuration options related to the RTF output
#---------------------------------------------------------------------------
# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The
# RTF output is optimized for Word 97 and may not look too pretty with other RTF
# readers/editors.
# The default value is: NO.
GENERATE_RTF = NO
# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: rtf.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_OUTPUT = rtf
# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF
# documents. This may be useful for small projects and may help to save some
# trees in general.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
COMPACT_RTF = NO
# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
# contain hyperlink fields. The RTF file will contain links (just like the HTML
# output) instead of page references. This makes the output suitable for online
# browsing using Word or some other Word compatible readers that support those
# fields.
#
# Note: WordPad (write) and others do not support links.
# The default value is: NO.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_HYPERLINKS = NO
# Load stylesheet definitions from file. Syntax is similar to doxygen's config
# file, i.e. a series of assignments. You only have to provide replacements,
# missing definitions are set to their default value.
#
# See also section "Doxygen usage" for information on how to generate the
# default style sheet that doxygen normally uses.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_STYLESHEET_FILE =
# Set optional variables used in the generation of an RTF document. Syntax is
# similar to doxygen's config file. A template extensions file can be generated
# using doxygen -e rtf extensionFile.
# This tag requires that the tag GENERATE_RTF is set to YES.
RTF_EXTENSIONS_FILE =
#---------------------------------------------------------------------------
# Configuration options related to the man page output
#---------------------------------------------------------------------------
# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for
# classes and files.
# The default value is: NO.
GENERATE_MAN = NO
# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it. A directory man3 will be created inside the directory specified by
# MAN_OUTPUT.
# The default directory is: man.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_OUTPUT = man
# The MAN_EXTENSION tag determines the extension that is added to the generated
# man pages. In case the manual section does not start with a number, the number
# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
# optional.
# The default value is: .3.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_EXTENSION = .3
# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
# will generate one additional man file for each entity documented in the real
# man page(s). These additional files only source the real man page, but without
# them the man command would be unable to find the correct page.
# The default value is: NO.
# This tag requires that the tag GENERATE_MAN is set to YES.
MAN_LINKS = NO
#---------------------------------------------------------------------------
# Configuration options related to the XML output
#---------------------------------------------------------------------------
# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that
# captures the structure of the code including all documentation.
# The default value is: NO.
GENERATE_XML = NO
# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
# it.
# The default directory is: xml.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_OUTPUT = xml
# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
# listings (including syntax highlighting and cross-referencing information) to
# the XML output. Note that enabling this will significantly increase the size
# of the XML output.
# The default value is: YES.
# This tag requires that the tag GENERATE_XML is set to YES.
XML_PROGRAMLISTING = YES
#---------------------------------------------------------------------------
# Configuration options related to the DOCBOOK output
#---------------------------------------------------------------------------
# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
# that can be used to generate PDF.
# The default value is: NO.
GENERATE_DOCBOOK = NO
# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
# front of it.
# The default directory is: docbook.
# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
DOCBOOK_OUTPUT = docbook
#---------------------------------------------------------------------------
# Configuration options for the AutoGen Definitions output
#---------------------------------------------------------------------------
# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen
# Definitions (see http://autogen.sf.net) file that captures the structure of
# the code including all documentation. Note that this feature is still
# experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_AUTOGEN_DEF = NO
#---------------------------------------------------------------------------
# Configuration options related to the Perl module output
#---------------------------------------------------------------------------
# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module
# file that captures the structure of the code including all documentation.
#
# Note that this feature is still experimental and incomplete at the moment.
# The default value is: NO.
GENERATE_PERLMOD = NO
# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary
# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
# output from the Perl module output.
# The default value is: NO.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_LATEX = NO
# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely
# formatted so it can be parsed by a human reader. This is useful if you want to
# understand what is going on. On the other hand, if this tag is set to NO the
# size of the Perl module output will be much smaller and Perl will parse it
# just the same.
# The default value is: YES.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_PRETTY = YES
# The names of the make variables in the generated doxyrules.make file are
# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
# so different doxyrules.make files included by the same Makefile don't
# overwrite each other's variables.
# This tag requires that the tag GENERATE_PERLMOD is set to YES.
PERLMOD_MAKEVAR_PREFIX =
#---------------------------------------------------------------------------
# Configuration options related to the preprocessor
#---------------------------------------------------------------------------
# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all
# C-preprocessor directives found in the sources and include files.
# The default value is: YES.
ENABLE_PREPROCESSING = YES
# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names
# in the source code. If set to NO only conditional compilation will be
# performed. Macro expansion can be done in a controlled way by setting
# EXPAND_ONLY_PREDEF to YES.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
MACRO_EXPANSION = YES
# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
# the macro expansion is limited to the macros specified with the PREDEFINED and
# EXPAND_AS_DEFINED tags.
# The default value is: NO.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_ONLY_PREDEF = YES
# If the SEARCH_INCLUDES tag is set to YES the includes files in the
# INCLUDE_PATH will be searched if a #include is found.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SEARCH_INCLUDES = YES
# The INCLUDE_PATH tag can be used to specify one or more directories that
# contain include files that are not input files but should be processed by the
# preprocessor.
# This tag requires that the tag SEARCH_INCLUDES is set to YES.
INCLUDE_PATH =
# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
# patterns (like *.h and *.hpp) to filter out the header-files in the
# directories. If left blank, the patterns specified with FILE_PATTERNS will be
# used.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
INCLUDE_FILE_PATTERNS =
# The PREDEFINED tag can be used to specify one or more macro names that are
# defined before the preprocessor is started (similar to the -D option of e.g.
# gcc). The argument of the tag is a list of macros of the form: name or
# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
# is assumed. To prevent a macro definition from being undefined via #undef or
# recursively expanded use the := operator instead of the = operator.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
PREDEFINED =
# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
# tag can be used to specify a list of macro names that should be expanded. The
# macro definition that is found in the sources will be used. Use the PREDEFINED
# tag if you want to use a different macro definition that overrules the
# definition found in the source code.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
EXPAND_AS_DEFINED =
# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
# remove all refrences to function-like macros that are alone on a line, have an
# all uppercase name, and do not end with a semicolon. Such function macros are
# typically used for boiler-plate code, and will confuse the parser if not
# removed.
# The default value is: YES.
# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
SKIP_FUNCTION_MACROS = YES
#---------------------------------------------------------------------------
# Configuration options related to external references
#---------------------------------------------------------------------------
# The TAGFILES tag can be used to specify one or more tag files. For each tag
# file the location of the external documentation should be added. The format of
# a tag file without this location is as follows:
# TAGFILES = file1 file2 ...
# Adding location for the tag files is done as follows:
# TAGFILES = file1=loc1 "file2 = loc2" ...
# where loc1 and loc2 can be relative or absolute paths or URLs. See the
# section "Linking to external documentation" for more information about the use
# of tag files.
# Note: Each tag file must have an unique name (where the name does NOT include
# the path). If a tag file is not located in the directory in which doxygen is
# run, you must also specify the path to the tagfile here.
TAGFILES =
# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
# tag file that is based on the input files it reads. See section "Linking to
# external documentation" for more information about the usage of tag files.
GENERATE_TAGFILE =
# If the ALLEXTERNALS tag is set to YES all external class will be listed in the
# class index. If set to NO only the inherited external classes will be listed.
# The default value is: NO.
ALLEXTERNALS = NO
# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in
# the modules index. If set to NO, only the current project's groups will be
# listed.
# The default value is: YES.
EXTERNAL_GROUPS = NO
# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in
# the related pages index. If set to NO, only the current project's pages will
# be listed.
# The default value is: YES.
EXTERNAL_PAGES = YES
# The PERL_PATH should be the absolute path and name of the perl script
# interpreter (i.e. the result of 'which perl').
# The default file (with absolute path) is: /usr/bin/perl.
PERL_PATH = /usr/bin/perl
#---------------------------------------------------------------------------
# Configuration options related to the dot tool
#---------------------------------------------------------------------------
# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram
# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
# NO turns the diagrams off. Note that this option also works with HAVE_DOT
# disabled, but it is recommended to install and use dot, since it yields more
# powerful graphs.
# The default value is: YES.
CLASS_DIAGRAMS = YES
# You can define message sequence charts within doxygen comments using the \msc
# command. Doxygen will then run the mscgen tool (see:
# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
# documentation. The MSCGEN_PATH tag allows you to specify the directory where
# the mscgen tool resides. If left empty the tool is assumed to be found in the
# default search path.
MSCGEN_PATH =
# If set to YES, the inheritance and collaboration graphs will hide inheritance
# and usage relations if the target is undocumented or is not a class.
# The default value is: YES.
HIDE_UNDOC_RELATIONS = YES
# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
# available from the path. This tool is part of Graphviz (see:
# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
# Bell Labs. The other options in this section have no effect if this option is
# set to NO
# The default value is: NO.
HAVE_DOT = NO
# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
# to run in parallel. When set to 0 doxygen will base this on the number of
# processors available in the system. You can set it explicitly to a value
# larger than 0 to get control over the balance between CPU load and processing
# speed.
# Minimum value: 0, maximum value: 32, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_NUM_THREADS = 0
# When you want a differently looking font n the dot files that doxygen
# generates you can specify the font name using DOT_FONTNAME. You need to make
# sure dot is able to find the font, which can be done by putting it in a
# standard location or by setting the DOTFONTPATH environment variable or by
# setting DOT_FONTPATH to the directory containing the font.
# The default value is: Helvetica.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTNAME = Helvetica
# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
# dot graphs.
# Minimum value: 4, maximum value: 24, default value: 10.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTSIZE = 10
# By default doxygen will tell dot to use the default font as specified with
# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
# the path where dot can find it using this tag.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_FONTPATH =
# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
# each documented class showing the direct and indirect inheritance relations.
# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
CLASS_GRAPH = YES
# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
# graph for each documented class showing the direct and indirect implementation
# dependencies (inheritance, containment, and class references variables) of the
# class with other documented classes.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
COLLABORATION_GRAPH = YES
# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
# groups, showing the direct groups dependencies.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GROUP_GRAPHS = YES
# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
# collaboration diagrams in a style similar to the OMG's Unified Modeling
# Language.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
UML_LOOK = NO
# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
# class node. If there are many fields or methods and many nodes the graph may
# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
# number of items for each type to make the size more manageable. Set this to 0
# for no limit. Note that the threshold may be exceeded by 50% before the limit
# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
# but if the number exceeds 15, the total amount of fields shown is limited to
# 10.
# Minimum value: 0, maximum value: 100, default value: 10.
# This tag requires that the tag HAVE_DOT is set to YES.
UML_LIMIT_NUM_FIELDS = 10
# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
# collaboration graphs will show the relations between templates and their
# instances.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
TEMPLATE_RELATIONS = NO
# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
# YES then doxygen will generate a graph for each documented file showing the
# direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDE_GRAPH = YES
# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
# set to YES then doxygen will generate a graph for each documented file showing
# the direct and indirect include dependencies of the file with other documented
# files.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
INCLUDED_BY_GRAPH = YES
# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable call graphs for selected
# functions only using the \callgraph command.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALL_GRAPH = NO
# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
# dependency graph for every global function or class method.
#
# Note that enabling this option will significantly increase the time of a run.
# So in most cases it will be better to enable caller graphs for selected
# functions only using the \callergraph command.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
CALLER_GRAPH = NO
# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
# hierarchy of all classes instead of a textual one.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GRAPHICAL_HIERARCHY = YES
# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
# dependencies a directory has on other directories in a graphical way. The
# dependency relations are determined by the #include relations between the
# files in the directories.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
DIRECTORY_GRAPH = YES
# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
# generated by dot.
# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
# to make the SVG files visible in IE 9+ (other browsers do not have this
# requirement).
# Possible values are: png, jpg, gif and svg.
# The default value is: png.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_IMAGE_FORMAT = png
# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
# enable generation of interactive SVG images that allow zooming and panning.
#
# Note that this requires a modern browser other than Internet Explorer. Tested
# and working are Firefox, Chrome, Safari, and Opera.
# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
# the SVG files visible. Older versions of IE do not have SVG support.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
INTERACTIVE_SVG = NO
# The DOT_PATH tag can be used to specify the path where the dot tool can be
# found. If left blank, it is assumed the dot tool can be found in the path.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_PATH =
# The DOTFILE_DIRS tag can be used to specify one or more directories that
# contain dot files that are included in the documentation (see the \dotfile
# command).
# This tag requires that the tag HAVE_DOT is set to YES.
DOTFILE_DIRS =
# The MSCFILE_DIRS tag can be used to specify one or more directories that
# contain msc files that are included in the documentation (see the \mscfile
# command).
MSCFILE_DIRS =
# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
# that will be shown in the graph. If the number of nodes in a graph becomes
# larger than this value, doxygen will truncate the graph, which is visualized
# by representing a node as a red box. Note that doxygen if the number of direct
# children of the root node in a graph is already larger than
# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
# Minimum value: 0, maximum value: 10000, default value: 50.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_GRAPH_MAX_NODES = 50
# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
# generated by dot. A depth value of 3 means that only nodes reachable from the
# root by following a path via at most 3 edges will be shown. Nodes that lay
# further from the root node will be omitted. Note that setting this option to 1
# or 2 may greatly reduce the computation time needed for large code bases. Also
# note that the size of a graph can be further restricted by
# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
# Minimum value: 0, maximum value: 1000, default value: 0.
# This tag requires that the tag HAVE_DOT is set to YES.
MAX_DOT_GRAPH_DEPTH = 0
# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
# background. This is disabled by default, because dot on Windows does not seem
# to support this out of the box.
#
# Warning: Depending on the platform used, enabling this option may lead to
# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
# read).
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_TRANSPARENT = NO
# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
# files in one run (i.e. multiple -o and -T options on the command line). This
# makes dot run faster, but since only newer versions of dot (>1.8.10) support
# this, this feature is disabled by default.
# The default value is: NO.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_MULTI_TARGETS = NO
# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
# explaining the meaning of the various boxes and arrows in the dot generated
# graphs.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
GENERATE_LEGEND = YES
# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot
# files that are used to generate the various graphs.
# The default value is: YES.
# This tag requires that the tag HAVE_DOT is set to YES.
DOT_CLEANUP = YES
================================================
FILE: docs/src/doxygen_layout.xml
================================================
================================================
FILE: docs/src/index.md
================================================
Games in Motion
===============
Games in Motion {#games_in_motion_index}
===============
[Games in Motion][] is a game that motivates people to run, walk and get fit. It
is a sample game with a goal to demonstrate different key game technologies.
It is developed entirely using [Android Studio][].
## Motivation
[Games in Motion][] demonstrates several Android-specific technologies,
including the [Google Fit][] API, the [Android Wear][] API, and a simple
data-driven design mechanism. [Games in Motion][] is also compatible with
[Material design][] UX system.
This sample shows how all these pieces can be put together in a fun context,
while also giving players a good motivation to exercise.
In addition, [fplutil][] is used to build the documentation of this project.
## Functionality
[Games in Motion][] is an open-source sample on [Android][] that demonstrates
* A fun game mechanic involving [Android Wear][],
* Game development in [Android Studio][],
* How to run a game entirely on a background service thread,
* [Google Fit][] API integration,
* [Android Wear][] API integration,
* [Google Play Games Services][] API integration,
* [Android Text to Speech][] API integration,
* [Android Audio Focus][] API integration,
* and JUnit test integration.
## Supported Platforms
[Games in Motion][] has been tested on the following platforms:
* [Android][] phones and tablets
We use [Android Studio][] and gradle to build. The game is written in Java with
data authored in XML.
## Download
[Games in Motion][] can be downloaded from:
* [GitHub][] (source)
* [GitHub Releases Page](http://github.com/googlesamples/android-play-games-in-motion/releases)
(source)
**Important**: Games in Motion uses submodules to reference other components it
depends upon, so download the source from [GitHub][] using:
~~~{.sh}
git clone --recursive https://github.com/googlesamples/android-play-games-in-motion.git
~~~
## Feedback and Reporting Bugs
* File issues on the [Games in Motion Issue Tracker][].
* Post your questions to [stackoverflow.com][] with a mention of
**gamesinmotion**.
\s\s
[Android]: http://developer.android.com
[Android Audio Focus]: http://developer.android.com/training/managing-audio/audio-focus.html
[Android Studio]: http://developer.android.com/tools/studio/index.html
[Android Text to Speech]: http://developer.android.com/reference/android/speech/tts/TextToSpeech.html
[Android Wear]: https://developer.android.com/wear/index.html
[fplutil]: http://google.github.io/fplutil/
[Games in Motion]: http://github.com/googlesamples/android-play-games-in-motion
[Games in Motion Issue Tracker]: http://github.com/googlesamples/android-play-games-in-motion/issues
[Google Fit]: https://developers.google.com/fit/
[Google Play Games Services]: https://developer.android.com/google/play-services/games.html
[GitHub]: http://github.com/googlesamples/android-play-games-in-motion
[Material design]: http://www.google.com/design/spec/material-design/introduction.html
[stackoverflow.com]: http://www.stackoverflow.com
================================================
FILE: docs/src/programmers_guide/assets.md
================================================
Modifying Assets {#games_in_motion_guide_assets}
================
### Overview
The game utilizes a data-driven component for gameplay. Games in Motion uses a
XML-based data component to describe missions.
To add a Mission, add a new XML file in the `app/src/main/assets/missions`
folder. There are existing XML files in both the `app/src/main/assets/missions`
and the `app/src/main/assets/legacy_missions` folders, which can be used as a
starting point.
The game loads gameplay assets from the `app/src/main/assets` directory, and
other assets (art, strings, layouts) from the `app/src/main/res` directory, as
is conventional in [Android Studio][].
### Authoring
As outlined at the [Mission][] system page, missions are comprised of moments.
Each moment signifies a different kind of event, and there is a `type` and an
`id` associated with each of them. Each kind of moment can define specific XML
tags. Optionally, each moment can have multiple `fictional_progress` tags, which
are information displayed to the user at the end of the mission.
Each mission has a `name` and a `start_id`. `start_id` signifies the first
moment of the mission. A mission progresses through its moments linearly, the
order of which is determined by the `next_moment_id` tag. The first moment will
always have an `id` identical to the mission's `start_id` property, whereas the
last moment will not have a `next_moment_id` tag.
For example, here is a simple mission with one moment:
0.5Played a mission!Played a timer moment
Here is a mission with two moments:
android.resource://com.google.fpl.gim.examplegame/raw/barBar!0.5
### Testing
There are simple unit tests written for the mission parser. The tests are in the
`app/src/androidTest` directory.
The tests can be run by changing the run configuration to `All Tests`.
\s\s
[Android Studio]: http://developer.android.com/tools/studio/index.html
[Mission]: @ref games_in_motion_guide_mission
================================================
FILE: docs/src/programmers_guide/audio.md
================================================
Audio {#games_in_motion_guide_audio}
=====
Audio is essential to [Games in Motion][]. It signals game progression to the
player, provides feedback for player actions, and allows the game to be played
without many physical interactions with a device.
We also want to let players choose their own background music.
[Games in Motion][] is designed to encourage people to move more, and often
background music helps set a pace for the activity.
In [Games in Motion][], audio is mostly handled by the [MainService][].
# Media Player {#games_in_motion_guide_mediaplayer}
We use [Android Media Player][] to control the playback of our raw audio files.
It is owned by [MainService][].
In this sample, we do not allow any sound effects to be played on top of each
other because all of them provide important user feedback. Therefore, we have
implemented an audio queue to make sure that only one sound effect is played at
a time.
Currently, only `SfxMoment` and `Mission` are queueing audio to be played by the
[Android Media Player][]. Any audio will only be played if we can properly
obtain [Audio Focus][].
# Text to Speech {#games_in_motion_guide_tts}
For certain game story elements, it is better to be able to author and change
them without having to re-record after every change. We use
[Android Text to Speech][] to generate audio from these texts.
The main Text to Speech module is owned by the [MainService][].
`SpokenTextMoment` obtains a reference to the module in order to convert its
text to audio and play it. Again, the audio will not be played unless we have
properly obtained [Audio focus][].
Unlike raw audio files, we cannot queue Text to Speech requests as easily.
Instead, we restart any `SpokenTextMoment` until we are successful in calling
the Text to Speech module.
# Audio Focus {#games_in_motion_guide_audiofocus}
A piece of audio, regardless of which module it is from, can only be played if
we satisfy these following conditions:
* No audio from the [Media Player][] or the [Text to Speech][] modules is
currently playing.
* We can obtain audio focus properly from the Android system.
The first condition is important so we are not overlapping any important audio
cues. The second is important because we want to make sure that the Android
system isn't performing any important audio tasks.
Because players can choose any background music from their favourite app, we
need to be able to lower the volume of any audio from other apps before we can
play our own. We return the volume level of those audio to previous levels once
we are done. We manage this by properly implementing Android Audio Focus. Please
review the [Managing Audio Focus][] page if you are not familiar with it.
\s\s
[Android Media Player]: http://developer.android.com/reference/android/media/MediaPlayer.html
[Android Text to Speech]: http://developer.android.com/reference/android/speech/tts/TextToSpeech.html
[Audio Focus]: @ref games_in_motion_guide_audiofocus
[Games in Motion]: @ref games_in_motion_index
[MainService]: @ref games_in_motion_guide_mainservice
[Managing Audio Focus]: http://developer.android.com/training/managing-audio/audio-focus.html
[Media Player]: @ref games_in_motion_guide_mediaplayer
[Text to Speech]: @ref games_in_motion_guide_tts
================================================
FILE: docs/src/programmers_guide/building.md
================================================
Building {#games_in_motion_guide_building}
========
Developers can build the game from source for [Android][], using
[Android Studio][].
# Version Requirements
Following are the minimum required versions for the tools and libraries you
need for building [Games in Motion][] for [Android][]:
- [Android Studio][]: Version 1.0.
- [Android SDK][]: Android 4.1 (API Level 16)
- [Android Support Library][]: v7.21
- [Google Play Games Services][]: 6.1 or above
- Install [fplutil prerequisites][] if you would like to build documentation.
# Before Building
- Install [Android Studio][].
- Install all required libraries via the Android SDK Manager from within
[Android Studio][].
## Set up Google Play Games Services
To use the [Google Play Games Services][] features in the game, follow the steps
below to set up [Google Play Games Services][] IDs:
- Create an App ID with new package name in the
[Google Play Developer Console][].
- Replace `app_id` in `app/build.gradle` with the newly created one.
- Update the package name in `app/src/AndroidManifest.xml` and Java source files.
- For example, rename `com.google.fpl.gim.examplegame` to
`com.mystudio.coolgame`.
- Add [Google Play Games Services][] to the App in the
[Google Play Developer Console][].
- For testing prior to publishing an APK, in the Game Services sections of the
[Google Play Developer Console][], add your email account as a tester.
# Building, installing, testing and running the game.
You can use the standard build and run instructions for [Android Studio][].
To build and run the JUnit tests, change the configuration from `app` to
`All Tests`.
\s\s
[Android]: http://www.android.com
[Android SDK]: http://developer.android.com/sdk/index.html
[Android Studio]: http://developer.android.com/tools/studio/index.html
[Android Support Library]: https://developer.android.com/tools/support-library/features.html
[fplutil prerequisites]: http://google.github.io/fplutil/fplutil_prerequisites.html
[Games in Motion]: @ref games_in_motion_guide_overview
[Google Play Developer Console]: http://play.google.com/apps/publish/
[Google Play Games Services]: https://developer.android.com/google/play-services/games.html
================================================
FILE: docs/src/programmers_guide/core.md
================================================
Games in Motion Core {#games_in_motion_guide_core}
====================
There are two main components of the game, `MainActivity` and `MainService`.
Find them in `app/src/main/java/com/google/fpl/gim/examplegame`.
# MainActivity
All Android applications have a main [Activity][] class which the application
will show on launch. Please review the [Activity Lifecycle][] if you are not
familiar with it.
For Games in Motion, `MainActivity` manages all the UI elements that are shown
on screen. It holds a pointer to `MainService` so it can query game state
changes in order to update the UI dynamically.
# MainService {#games_in_motion_guide_mainservice}
`MainService` is included in `AndroidManifest.xml`. It will automatically be
started when the app is launched. Please review the [Service Basics][] if you
are not familiar with Services. `MainService` is run in the background to allow
the game to continue running when the player turns off the phone screen, or when
`MainActivity` is paused for any reason.
`MainService::Run` contains the main game loop. Every call to that function is
one frame of the game update.
`MainService` holds references to all the key systems that are needed during
gameplay. This includes the [Mission system][], [Android Audio Manager][],
[Android Text to Speech][], and the [Google Api Wrapper][]. `MainService` is
also responsible for starting up these systems and channeling queries to them.
# UI
Most of Games in Motion's UI is handled using [Fragments][].
`MainActivity` holds all the fragments and handles all incoming requests to
advance the UI, or delegate them to the fragments. The UI fragments reside in
`app/src/main/java/com/google/fpl/gim/examplegame/gui`.
Games in Motion also uses [Notifications][] extensively. They allow the user to
interact with the game, either through the notifications menu, or an Android
Wear device. Notifications are typically issued through `MainService` as they
can occur while `MainActivity` is not in display.
# State Machine
There is a simple state machine that resides in `MainService`. The `mState`
variable dictates the mission flow. There are two functions that help control
the states: `canEnterState` checks if we can enter a state from the current
state, and `setAndInitNextState` sets the state machine to the next state while
doing all the initializations needed for the transition. The states and their
transitions are described below.
* `UNINITIALIZED` -- No mission is loaded. The player is still going through
the UI flow and hasn't started a game mission yet.
You can enter this state from any other states. It happens when the player
hit the back button from `END_SCREEN`, when the connection to Google Apis
has been disconnected, or when some other sort of error has occurred.
* `MISSION_LOADED` -- The game mission has been loaded and we are waiting for
a few key systems to finish starting up before we start the mission.
When the player starts a mission, it will trigger a load from the `assets`
folder. It will also trigger subscriptions to the appropriate [Google Fit][]
data streams.
When the game is ready, the game transitions to `MISSION_RUNNING`.
* `MISSION_RUNNING` -- The misson is started when we transition to this state.
While in this state, the mission is also running, even if the device screen
is not on.
This state can only be transitioned from `MISSION_LOADED`.
* `END_SCREEN` -- When a mission is over (all its moments have been played),
or when a player aborts a mission by hitting the back button, the game will
transition to this state.
The game will display the statistics from the mission while in this state.
This state can only be transitioned from `MISSION_RUNNING`.
\s\s
[Activity]: http://developer.android.com/reference/android/app/Activity.html
[Activity Lifecycle]: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
[Android Audio Manager]: http://developer.android.com/reference/android/media/AudioManager.html
[Android Text to Speech]: http://developer.android.com/reference/android/speech/tts/TextToSpeech.html
[Fragments]: http://developer.android.com/reference/android/app/Activity.html#Fragments
[Google Api Wrapper]: @ref games_in_motion_guide_google_api
[Google Fit]: https://developers.google.com/fit/
[Mission system]: @ref games_in_motion_guide_mission
[Notifications]: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
[Service Basics]: http://developer.android.com/guide/components/services.html
================================================
FILE: docs/src/programmers_guide/gameplay.md
================================================
Gameplay {#games_in_motion_guide_gameplay}
===============
The player selects a mission to play and exercises (walk or run) while receiving
audio cues on gameplay.
The player can customize their experience based on their fitness level and
goals. In order to fulfill the player's exercise goals, they can select an
interval speed they want to challenge. If the player wants to listen to music
while running, they can switch over to their favourite music app and start
playing the music before starting a mission.
While on a mission, the player listens to mission details, learning about the
story and what the game goals are. When it comes time to interact with the game,
the player will make choices by tapping or swiping on their [Android Wear][]
device or the notifications menu of their phone or tablet.
If the player has been consistently running at the interval speed,
they will be rewarded with extra choices.
Upon completion of the mission, the app presents the statistics of the exercise
and uploads the data to [Google Fit][].
\s\s
[Android Wear]: https://developer.android.com/wear/index.html
[Google Fit]: https://developers.google.com/fit/
================================================
FILE: docs/src/programmers_guide/google_api.md
================================================
Google API {#games_in_motion_guide_google_api}
==========
Google APIs provide feature access that is important to Games in Motion. These
APIs are accessed using the [GoogleApiClient][] which handles all connections to
Google-provided services.
The `GoogleApiClientWrapper` class handles all connections to
[GoogleApiClient][]. Find it in
`app/src/main/java/com/google/fpl/gim/examplegame/google`.
At start up, Games in Motion attempts to connect to various Google API services.
The connection flow is delegated to the appropriate service by default.
# Google Fit
[Google Fit][] is a core part of Games in Motion. It keeps track of step count,
tracks speed, and keeps data in the cloud so the player can retrieve it via
other apps that connect to [Google Fit][].
When the player is ready to start a mission, Games in Motion connects to
[Google Fit][] to register callbacks for step count and speed. When all the
sensors are connected properly (detected via callbacks), Games in Motion start
the mission.
Note that for certain Android devices, there might be a noticeable delay between
successfully registering a sensor and actually getting sensor data. If the
device has hardware sensors: the sensors might take some time to start up. Games
in Motion does not account for the delay.
For tracking speed, Games in Motion provide a fallback mechanism to calculating
speed in case sensor data is unreliable.
# Google Play Games Service
In the `GoogleApiClientWrapper` class, Games in Motion connects to
[Google Play Games Services][] in the same manner as it connects to
[Google Fit][]. Games in Motion provides an example of unlocking achievements.
Look for the `unlockAchievement` method in `MainService.java`.
\s\s
[GoogleApiClient]: https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.html
[Google Fit]: https://developers.google.com/fit/
[Google Play Games Services]: https://developer.android.com/google/play-services/games.html
================================================
FILE: docs/src/programmers_guide/mission.md
================================================
Mission System {#games_in_motion_guide_mission}
==============
The data-driven mission system is controlled by the `Mission` class. Only one
`Mission`, consisting of a list `Moments`, may be active at any point during
gameplay. Only one `Moment` is active at a time while the player plays.
Each of the data-driven classes (`Mission` and various `Moment` classes) has
an equivalent Data class that contains the actual data parsed from the input XML
files. Find them in `app/src/main/java/com/google/fpl/gim/examplegame`.
# Mission
`Mission` keeps track of the game progression, as well as all the data generated
by the user during the game. Its `update()` method is being called by
`MainService` per game frame, and it will trigger the relevant `Moment`s as time
progresses.
On mission start, `Mission` will register listeners with [Google Fit][]. This
allows us to obtain speed and step data, which is critical to the game.
# Moment
A `Moment` is a discrete event within a `Mission`. `Moment`s know when they
finish, the next `Moment` to start, are sequential, and are never reused.
We have implemented a few types of `Moment`s for a basic mission flow.
* Choice moments.
These give the player a couple choices to choose from. The choices are
shown to players as [Notifications][].
* Sfx moments.
These queue a simple sound effect to be played.
* Spoken Text moments.
These use [Android Text to Speech][] to generate spoken speech to be played
when the app gets [Audio Focus][].
* Timer moments.
These are simple timers to space out the other `Moment`s.
As you can see, each of these `Moment`s are small encapsulated game events. They
are highly specialized, but can be authored to allow for variety and flexibility
in each game mission.
# Parser
In order to parse our custom data formats for `Mission`s and `Moment`s, we have
written a `MissionParser`. Find it in
`app/src/main/java/com/google/fpl/gim/examplegame/utils`.
This is a runtime parser that will parse XML data when the player selected a
mission. It is also the only component that has unit testing. Find the test in
`app/src/androidTest/`.
\s\s
[Android Text to Speech]: http://developer.android.com/reference/android/speech/tts/TextToSpeech.html
[Audio Focus]: http://developer.android.com/training/managing-audio/audio-focus.html
[Google Fit]: https://developers.google.com/fit/
[Notifications]: http://developer.android.com/guide/topics/ui/notifiers/notifications.html
================================================
FILE: docs/src/programmers_guide/overview.md
================================================
Overview {#games_in_motion_guide_overview}
========
## Downloading
[Games in Motion][] can be downloaded from [GitHub](http://github.com/googlesamples/android-play-games-in-motion)
or the [releases page](http://github.com/googlesamples/android-play-games-in-motion/releases).
~~~{.sh}
git clone --recursive https://github.com/googlesamples/android-play-games-in-motion.git
~~~
## Subsystems
Games in Motion code is divided into the following subsystems
- [Core][] -- holds game subsystems, state, and state machine, and UI.
- [Mission System][] -- a simple, game-agnostic system for organizing game
events.
- [Google Api][] -- an interface with different Google services APIs.
- [Audio][] -- various systems integrated to produce audio and control focus.
## Source Layout
The following bullets describe the directory structure of the game.
| Path | Description |
|-------------------------------|----------------------------------------------|
| base directory | Android Studio project files. |
| `app/main` | Main directory for all code and assets. |
| `app/main/assets` | Game mission data in .xml format. |
| `app/main/java` | Where the main code lives. |
| `app/main/res` | Android-style assets. |
| `app/androidTest` | JUnit tests for the mission authoring |
| | component. |
| `docs` | Documentation source and html files. |
\s\s
[Audio]: @ref games_in_motion_guide_audio
[Core]: @ref games_in_motion_guide_core
[Games in Motion]: @ref games_in_motion_index
[Google Api]: @ref games_in_motion_guide_google_api
[Mission System]: @ref games_in_motion_guide_mission
================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# 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.
#
#Fri Jan 09 12:15:18 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip
================================================
FILE: gradle.properties
================================================
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# 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.
#
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Settings specified in this file will override any Gradle settings
# configured through the IDE.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
================================================
FILE: gradlew
================================================
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >&-
APP_HOME="`pwd -P`"
cd "$SAVED" >&-
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
================================================
FILE: prototype.iml
================================================
================================================
FILE: readme.md
================================================
Games in Motion {#games_in_motion_readme}
===============
Games in Motion Version 1.0.0
[Games in Motion][] is a simple game that motivates you to run.
## Motivation
[Games in Motion][] is a demonstration for several Android-specific
technologies, including the [Google Fit][] API, the [Android Wear][] API, and a
simple data-driven design mechanic. It is also compatible with
[Material design][]. This sample shows how all these pieces can be put together
in a fun context, while also giving players a good motivation to exercise.
[Games in Motion][] is developed entirely using [Android Studio][].
## Downloading
[Games in Motion][] can be downloaded from:
* [GitHub][] (source)
* [GitHub Releases Page](http://github.com/googlesamples/android-play-games-in-motion/releases) (source)
~~~{.sh}
git clone --recursive https://github.com/googlesamples/android-play-games-in-motion.git
~~~
## Documentation
The documentation is include with the GitHub codebase. It is in the `docs`
directory.
Required libraries:
* Python 2.7
* [fplutil][] library
[fplutil][] is referenced as a submodule from the [Games in Motion][]
repository, so the download command referenced above will automatically download
it as well.
After all required libraries are downloaded, run:
~~~{.sh}
./docs/generate_docs.py
~~~
The generated documentation will be in `docs/html`.
To contribute the this project see [CONTRIBUTING][]. The license file is at
[LICENSE][].
\s\s
[Android Studio]: http://developer.android.com/tools/studio/index.html
[Android Wear]: https://developer.android.com/wear/index.html
[Build and Run Games in Motion]: http://github.com/googlesamples/android-play-games-in-motiongames_in_motion_guide_building.html
[fplutil]: http://google.github.io/fplutil/
[Games in Motion]: http://github.com/googlesamples/android-play-games-in-motion
[Google Fit]: https://developers.google.com/fit/
[Material design]: http://www.google.com/design/spec/material-design/introduction.html
[Programmer's Guide]: http://github.com/googlesamples/android-play-games-in-motion/games_in_motion_guide_overview.html
[CONTRIBUTING]: http://github.com/googlesamples/android-play-games-in-motion/blob/master/CONTRIBUTING
[LICENSE]: http://github.com/googlesamples/android-play-games-in-motion/blob/master/LICENSE
[GitHub]: http://github.com/googlesamples/android-play-games-in-motion
================================================
FILE: settings.gradle
================================================
/*
* Copyright 2015 Google Inc. All Rights Reserved.
*
* 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.
*/
include ':app'