feat: stats graphs, playtime, ip search against ban evasion, 150-char chat

- stats graphs for the admin and moderator panels (lib/stats.js, public/stats-view.html)
- playtime, private unless shown on the card's bio tab; set on the account page
- search accounts by ip address, only against ban evasion; mods see no addresses and each search is logged
- privacy policy for the above (terms version 2026-10-17)
- the per-second save looks only at accounts in play, with a slow sweep of the rest
- items in several dens at once; chat filter hides slurs and threats by default
- sexual usernames refused; moderators may enter full rooms; guide login allowed
- 150-character chat box (client build 55)
- fixes: gifts, trades, dens, pets in dens, den recycling, special animals' colours,
  jammer walls, settings switches; the buddy list sent at login
- the item giver, the rules screen and the art studio rework
This commit is contained in:
Burrowdev committed 2026-10-17 02:00:57 +03:00
1 parent 8400d2f928
commit 04f468af2c
56 files changed
+25667 -3894

No files matched your search

+4 -2
View File
@@ -114,7 +114,9 @@ module.exports = {
// game no longer open to SWFs from other addresses.
// 40: the chat filter's window laid out again.
// 41: the game's text says "Burrow" where it said Animal Jam.
buildVersion: env.AJ_BUILD_VERSION || "41",
// 48: the item giver (the item finder renamed) with previews and hex colours;
// 49 and 50: its link to a colour picker.
buildVersion: env.AJ_BUILD_VERSION || "55",
// what the official CDN is asked for; not ours to change.
upstreamBuildVersion: "3",
@@ -147,7 +149,7 @@ module.exports = {
// are written into both pages. the emails and the host's country are
// placeholders until set; the operator is, at the owner's word, said to
// be in the EU without a name or a country.
termsVersion: "2026-10-13",
termsVersion: "2026-10-17",
legalEmail: env.AJ_LEGAL_EMAIL || "[email protected]",
adminEmail: env.AJ_ADMIN_EMAIL || "[email protected]",
operator: env.AJ_OPERATOR || "an individual based in the European Union",
+148 -22
View File
@@ -56,6 +56,10 @@ const MIN_LETTERS = 3; // the client's own rule (SbiConstants.USERNAME_REGEX)
const MIN_PASSWORD_LENGTH = 10;
const MAX_DEN_SLOTS = 200; // DenSwitch.nextFreeSlotIdx
const DEN_OPEN = 2; // den privacy: 0 locked, 1 buddies only, 2 everyone
const USER_VAR_SETTINGS = 363; // the settings menu's switches, a bit each (gui.MySettings)
// the chat filter an account starts with: level 1 slurs and threats, mode 1
// the whole message left out (see account.filter below).
const DEFAULT_FILTER = {level: 1, mode: 1, words: ""};
const MAX_PASSWORD_LENGTH = 100;
// parts of the game a player can switch off for their own account, each
// enforced where the game asks for it (featureOn below).
@@ -109,7 +113,7 @@ const newAvatar = (ids, name, type, customAvId) => {
customAvId: custom ? Number(customAvId) : -1,
colors: [def.colorLayer1, Number(custom && custom.overrideColorLayer2) || def.colorLayer2, def.colorLayer3].map(Number),
eyes: Number(def.baseEyesId) || 0,
pattern: Number(custom ? custom.patternRefId : def.basePatternId) || 0,
pattern: Number(custom ? defpacks.customPattern(customAvId) : def.basePatternId) || 0,
petInvId: 0,
};
};
@@ -153,6 +157,10 @@ const normalize = account => {
account.outfitUndo.avInvId = avatar.avInvId;
}
}
// custom animals made while their pattern list was a 0 (lib/defpacks.js)
for (const avatar of account.avatars.filter(candidate => candidate.customAvId !== -1 && !candidate.pattern)) {
avatar.pattern = defpacks.customPattern(avatar.customAvId);
}
account.pets = account.pets || []; // {inv, lBits, uBits, eBits, name, createdAt}
account.dens = account.dens || [{inv: 0, def: config.denDefId}]; // den rooms owned
account.activeDen = account.activeDen || 0; // inv of the den in use
@@ -174,14 +182,34 @@ const normalize = account => {
account.activeDen = moved.has(account.activeDen) ? moved.get(account.activeDen) : account.activeDen;
for (const item of account.denItems || []) {
item.den = moved.has(item.den) ? moved.get(item.den) : item.den;
if (item.spots) {
item.spots = Object.fromEntries(Object.entries(item.spots).map(([den, spot]) => [moved.has(Number(den)) ? moved.get(Number(den)) : den, spot]));
}
}
}
account.denPrivacy = account.denPrivacy === undefined ? DEN_OPEN : account.denPrivacy;
account.denItems = account.denItems || []; // {inv, def, version, placed, den, x, y, flip, mannequin?, image?}: lib/dens.js
// {inv, def, version, spots, mannequin?, image?}: lib/dens.js. spots: where
// it stands, {den inventory id: {cat, x, y, flip}}, as many dens as it is in.
account.denItems = account.denItems || [];
for (const item of account.denItems) {
item.den = item.den === undefined ? account.activeDen : item.den; // which den it is placed in
// from when an item stood in one den at most: {placed, den, x, y, flip, cat}.
if (!item.spots) {
const den = item.den === undefined ? account.activeDen : item.den;
item.spots = item.placed ? {[den]: {cat: item.cat || 1, x: item.x || 0, y: item.y || 0, flip: item.flip || 0}} : {};
}
for (const old of ["placed", "den", "x", "y", "flip", "cat"]) {
delete item[old];
}
}
account.userVars = account.userVars || {};
// the settings menu's switches (user var 363) were once stored as the
// number of the last switch touched rather than as bits: such a value
// cannot be told from a real one, so every account starts again from the
// game's defaults, once.
if (!account.settingsBitsFixed) {
delete account.userVars[USER_VAR_SETTINGS];
account.settingsBitsFixed = true;
}
account.theme = account.theme || ""; // seasonal look of the lands, see themes in config.js
account.lastSeen = account.lastSeen || 0; // when they last left the game, in seconds; 0 = never recorded
// what the player set on the account page (lib/manage.js).
@@ -219,12 +247,25 @@ const normalize = account => {
account.discord = typeof account.discord === "string" ? account.discord : ""; // their Discord username, as they gave it
account.badges = Array.isArray(account.badges) ? account.badges : []; // badge ids, given in the admin panel
account.bio = typeof account.bio === "string" ? account.bio : ""; // their own words, for the card's Bio tab
// seconds spent in the game in all (lib/world.js counts it), and whether
// their card shows it to others: theirs to choose on the account page.
account.playtime = Number.isFinite(account.playtime) && account.playtime > 0 ? Math.floor(account.playtime) : 0;
account.playtimePublic = account.playtimePublic === true;
// the chat filter, which the player's own game applies (AJClient in the
// patched SWF; "xfl" in lib/world.js): {level: 1 slurs and threats, 2
// swearing too, 0 off; mode: 0 stars over the words, 1 the message left
// out; words: their own, commas between; chosen: have they been asked}.
// an account that has not chosen has no filter: that is the start.
account.filter = account.filter && typeof account.filter === "object" && account.filter.chosen ? account.filter : {level: 0, mode: 0, words: "", chosen: false};
// an account starts with slurs and threats hidden, and may turn it off.
account.filter = account.filter && typeof account.filter === "object" && account.filter.chosen ? account.filter : {...DEFAULT_FILTER, chosen: false};
// that default came after accounts that had none, or had turned it off:
// they get it too, once. a stricter level, and the way it is shown when
// they had one, stay as they were.
if (!account.filterDefaultApplied) {
if (!(account.filter.level >= DEFAULT_FILTER.level)) {
Object.assign(account.filter, {level: DEFAULT_FILTER.level, mode: DEFAULT_FILTER.mode});
}
account.filterDefaultApplied = true;
}
// two-step sign-in: lib/totp.js.
account.totp = account.totp || null;
account.totpSetup = account.totpSetup || null;
@@ -245,11 +286,13 @@ const MAX_START_ROOM = 80;
function setLoginChoices(account, choices) {
const asked = config.loginChoices && choices && typeof choices === "object" ? choices : {};
const whole = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
// member or not is the player's own choice on any server, the rest only
// with config.loginChoices: another account type shows to everyone.
const type = choices && typeof choices === "object" && MEMBERSHIP_TYPES.includes(choices.accountType) ? choices.accountType : asked.accountType;
// member or not, and guide or not, are the player's own choice on any
// server; the rest only with config.loginChoices: another account type
// shows to everyone.
const own = choices && typeof choices === "object" ? choices : {};
const type = MEMBERSHIP_TYPES.includes(own.accountType) ? own.accountType : asked.accountType;
account.accountType = whole(type, MAX_ACCOUNT_TYPE) ? type : config.defaultAccountType;
account.isGuide = asked.isGuide === true;
account.isGuide = own.isGuide === true;
account.isModerator = asked.isModerator === true;
account.membershipDays = whole(asked.membershipDays, MAX_MEMBERSHIP_DAYS) ? asked.membershipDays : DEFAULT_MEMBERSHIP_DAYS;
// where to start is the player's to say on any server: their own den in
@@ -277,6 +320,7 @@ const insert = (username, salt, hash, createdAt, state) => {
account.id = Number(result.lastInsertRowid);
savedState.set(account.id, json);
remember(account);
touch(account);
return account;
};
@@ -371,20 +415,101 @@ const load = () => {
console.log(`[accounts] ${byKey.size} accounts in ${path.join(config.dataDir, "game.sqlite")}`);
};
// Which accounts the save after a message looks at. turning an account into
// JSON to see whether it changed costs, and doing it for every account there
// is, a second after nearly every message, held the whole server up for
// longer the more accounts there were: a second and more, for everyone. so
// it looks at the accounts in play: online ones (hold, from lib/world.js),
// and ones looked up lately (by name, id, token, password: how the admin
// panel, buddies and the like get at an offline account), until a save
// finds them written and WARM_MS has gone by. the rest are looked at a few
// at a time behind those (SWEEP_BUDGET_MS a save), round and round, for
// what reached an account some other way (accounts.all()). a stop of the
// server, and every flush() called by name, looks at all of them.
const WARM_MS = 10 * 60 * 1000;
const SWEEP_BUDGET_MS = 5;
const held = new Set(); // accounts online
const warm = new Map(); // account -> when last looked up
let sweepOrder = [];
let sweepAt = 0;
let sweepLeft = 0; // accounts the sweep still has to look at since the last save()
const touch = account => {
if (account) {
warm.set(account, Date.now());
}
return account;
};
const hold = account => {
held.add(account);
touch(account);
};
const release = account => {
held.delete(account);
touch(account);
};
const changedState = (account, changed) => {
const json = stateJson(account);
if (savedState.get(account.id) !== json) {
changed.push([account.id, json]);
return true;
}
return false;
};
// writes every account whose state changed since it was last written, in
// one transaction.
const flush = () => {
// one transaction; with {some: true}, of the accounts in play and the
// sweep's next few (above).
const flush = ({some = false} = {}) => {
clearTimeout(saveTimer);
saveTimer = null;
if (!db) {
return;
}
const changed = [];
for (const account of byId.values()) {
const json = stateJson(account);
if (savedState.get(account.id) !== json) {
changed.push([account.id, json]);
if (some) {
const now = Date.now();
const looked = new Set();
for (const account of held) {
looked.add(account);
changedState(account, changed);
}
for (const [account, at] of warm) {
if (looked.has(account)) {
continue;
}
looked.add(account);
if (byId.get(account.id) !== account) {
warm.delete(account); // removed
}
else if (!changedState(account, changed) && now - at > WARM_MS && !held.has(account)) {
warm.delete(account);
}
}
const started = process.hrtime.bigint();
while (sweepLeft > 0 && Number(process.hrtime.bigint() - started) / 1e6 < SWEEP_BUDGET_MS) {
if (sweepAt >= sweepOrder.length) {
sweepOrder = [...byId.values()];
sweepAt = 0;
if (sweepOrder.length === 0) {
break;
}
}
const account = sweepOrder[sweepAt++];
sweepLeft--;
if (!looked.has(account) && byId.get(account.id) === account) {
changedState(account, changed);
}
}
}
else {
for (const account of byId.values()) {
changedState(account, changed);
}
sweepLeft = 0;
}
if (sweepLeft > 0) {
save(); // the sweep goes on in a moment
}
if (changed.length === 0) {
return;
@@ -415,10 +540,11 @@ const flush = () => {
const SAVE_DELAY_MS = 1000;
let saveTimer = null;
const save = () => {
sweepLeft = byId.size;
if (saveTimer === null) {
saveTimer = setTimeout(() => {
try {
flush();
flush({some: true});
}
catch (err) {
console.error(`[accounts] could not save: ${err.message}`);
@@ -512,7 +638,7 @@ const register = (username, password, avatar = {}) => {
const authenticate = (username, password) => {
// "name" and "name " are the same account.
const account = typeof username === "string" ? byKey.get(username.trim().toLowerCase()) : null;
const account = typeof username === "string" ? touch(byKey.get(username.trim().toLowerCase())) : null;
if (typeof password !== "string" || !password) {
return null;
}
@@ -534,7 +660,7 @@ const authenticate = (username, password) => {
// the same, with the password worked out off the main thread (above).
const authenticateAsync = async (username, password) => {
const account = typeof username === "string" ? byKey.get(username.trim().toLowerCase()) : null;
const account = typeof username === "string" ? touch(byKey.get(username.trim().toLowerCase())) : null;
if (typeof password !== "string" || !password || password.length > MAX_PASSWORD_LENGTH) {
return null;
}
@@ -684,15 +810,15 @@ const issueToken = account => {
const byToken = token => {
const entry = typeof token === "string" && token.length === TOKEN_HEX_LENGTH ? tokens.get(tokenHash(token)) : null;
return entry && !tokenExpired(entry.createdAt) ? byId.get(entry.id) || null : null;
return entry && !tokenExpired(entry.createdAt) ? touch(byId.get(entry.id)) || null : null;
};
const byName = username => byKey.get(String(username).toLowerCase()) || null;
const byName = username => touch(byKey.get(String(username).toLowerCase())) || null;
const accountById = id => byId.get(Number(id)) || null;
const accountById = id => touch(byId.get(Number(id))) || null;
const all = () => [...byId.values()];
const database = () => db;
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, byId: accountById, newAvatar, freeAvatarSlot, all};
module.exports = {FEATURES, featureOn, recordLogin, revokeTokens, load, save, flush, hold, release, startBackups, database, setLoginChoices, setPassword, rename, remove, setting, setSetting, hashPassword, register, usernameProblem, authenticate, authenticateAsync, issueToken, byToken, byName, byId: accountById, newAvatar, freeAvatarSlot, all};
+25 -6
View File
@@ -53,6 +53,10 @@ const search = (params, favourites = null) => {
};
};
// one to four "#RRGGBB", spaces or commas between. the # is wanted: six
// digits alone are a colour id
const HEX_COLOURS = /^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i;
const give = body => {
const account = accounts.byName(body.username);
if (!account) {
@@ -62,13 +66,28 @@ const give = body => {
if (body.kind === "clothing") {
const def = defpacks.itemDef(body.id);
const colors = def ? String(def.colors).split(",") : [];
// `color` is a raw colour id of the caller's choosing; otherwise one of
// the item's own colours is picked by `colorIndex`.
const custom = body.color !== undefined && body.color !== "";
if (custom && !isUint(String(body.color))) {
return {status: 400, body: {error: "The colour id must be a whole number from 0 to 4294967295"}};
// `color` is a raw colour id of the caller's choosing, or one to four hex
// colours ("#FF8800", "#FF0000 #FFFFFF") for the item's four colour bands
// in order, the last filling the rest: a custom colour (lib/colours.js),
// made as the animal editor's hex box makes one. otherwise one of the
// item's own colours is picked by `colorIndex`.
let custom = body.color !== undefined && body.color !== "" ? String(body.color).trim() : "";
const hexes = custom.match(HEX_COLOURS) ? custom.split(/[\s,]+/).filter(Boolean) : null;
if (hexes) {
const rgbs = [0, 1, 2, 3].map(slot => parseInt(hexes[Math.min(slot, hexes.length - 1)].replace("#", ""), 16));
const entry = world.makeColour(account, rgbs, session);
if (!entry) {
return {status: 400, body: {error: "Bad colour"}};
}
if (entry.full) {
return {status: 429, body: {error: "No more new colours today. Colours made before can still be used."}};
}
custom = String(entry.id);
}
const color = custom ? String(body.color) : colors[Number(body.colorIndex) || 0];
if (custom && !isUint(custom)) {
return {status: 400, body: {error: "Colour: an id, or #RRGGBB"}};
}
const color = custom || colors[Number(body.colorIndex) || 0];
if (!def || !defpacks.clothingIds().includes(Number(def.id)) || color === undefined) {
return {status: 400, body: {error: "No such clothing item or colour"}};
}
+11 -10
View File
@@ -166,22 +166,22 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
const activeDenDef = account => (account.dens.find(den => den.inv === account.activeDen) || account.dens[0]).def;
const layoutOf = owner => owner.denItems
.filter(item => item.placed && item.den === owner.activeDen)
.map(item => ({def: item.def, version: item.version, x: item.x, y: item.y, flip: item.flip}));
.filter(item => dens.spotOf(item, owner.activeDen))
.map(item => ({def: item.def, version: item.version, ...dens.spotOf(item, owner.activeDen)}));
// lays the account's den in use out as `layout` says, with its own items.
// with `giveMissing`, items it lacks are added to its inventory first.
// returns how many of the layout's items could not be placed.
// lays the account's den in use out as `layout` says, with its own items
// (whether or not they stand in other dens too). with `giveMissing`, items
// it lacks are added to its inventory first. returns how many of the
// layout's items could not be placed.
const applyLayout = (session, layout, giveMissing) => {
const {account} = session;
for (const item of account.denItems.filter(candidate => candidate.den === account.activeDen)) {
item.placed = false;
item.x = item.y = item.flip = 0;
for (const item of account.denItems.filter(candidate => dens.spotOf(candidate, account.activeDen))) {
delete item.spots[account.activeDen];
}
const used = new Set();
let missing = 0;
for (const spot of layout) {
let item = account.denItems.find(candidate => !used.has(candidate) && !candidate.placed
let item = account.denItems.find(candidate => !used.has(candidate)
&& candidate.def === spot.def && candidate.version === spot.version);
if (!item && giveMissing && account.denItems.length < MAX_DEN_ITEMS && defpacks.denItemIds().includes(spot.def)) {
item = dens.giveDenItem(account, spot.def, spot.version);
@@ -191,7 +191,8 @@ module.exports = ({findOnline, players, watchers, sendItemList, blocks, setHideB
continue;
}
used.add(item);
Object.assign(item, {placed: true, den: account.activeDen, x: spot.x, y: spot.y, flip: spot.flip});
item.spots = item.spots || {};
item.spots[account.activeDen] = {cat: spot.cat || 1, x: spot.x, y: spot.y, flip: spot.flip};
}
accounts.save();
dens.sendDenItems(session);
+20 -1
View File
@@ -19,6 +19,19 @@ const DEF_DEN_ROOM = 1040;
const DEF_DIAMOND = 1054;
const DEF_PET = 1046;
const DEF_AVATAR_CUSTOM = 1057;
// custom animals whose def has no pattern (patternRefId 0): their patterns
// were only in the generic list the official server sent. these are the
// pattern items locked to a special animal (bLockAvatarFlags) made after
// the last def that names its own, in release order; 2121 starts with the
// raccoon's overrideColorLayer2. a list of 0 made the avatar editor throw
// (#1009 in AvatarEditor.setCustomPatternColorIdx) and never open.
const CUSTOM_PATTERNS = new Map([
[8, [1963, 1964, 1965, 1966]], // Legendary Eagle
[9, [1976]], // Fearsome Falcon
[10, [1981]], // Royal Red Panda
[11, [2073]], // Frolicking Fox
[12, [2121]], // Rainbow Raccoon
]);
const DEF_ACHIEVEMENTS = 1042;
const DEF_PARTY = 1047;
const DEF_CURRENCY_EXCHANGE = 1051;
@@ -398,7 +411,8 @@ const init = async () => {
customAvatarDefs = new Map((await load(DEF_AVATAR_CUSTOM)).map(def => [Number(def.id), def]));
for (const def of await load(DEF_AVATAR_CUSTOM)) {
const listId = Number(def.patternListRefId);
patternLists.set(listId, [...(patternLists.get(listId) || []), Number(def.patternRefId)]);
const patterns = Number(def.patternRefId) ? [Number(def.patternRefId)] : CUSTOM_PATTERNS.get(Number(def.id)) || [];
patternLists.set(listId, [...(patternLists.get(listId) || []), ...patterns]);
}
roomDefsById = new Map((await load(DEF_ROOM)).map(def => [Number(def.id), def]));
// typeCat 4 is music (the jukebox tracks; also what a hosted party plays)
@@ -487,6 +501,11 @@ module.exports = {
extraMusicIds: () => extraMusic.ids,
roomDefById: id => roomDefsById.get(Number(id)),
patternList: listId => patternLists.get(Number(listId)),
// the pattern a custom animal starts with
customPattern: id => {
const def = customAvatarDefs.get(Number(id));
return def ? (patternLists.get(Number(def.patternListRefId)) || [0])[0] : 0;
},
avatarTypes: () => [...avatarDefs.keys()],
// first non-member land animal, falling back to whatever the pack lists
// first.
+127 -32
View File
@@ -30,7 +30,10 @@ const canEnter = (owner, visitor) => owner === visitor || owner.denPrivacy === D
|| (owner.denPrivacy === DEN_BUDDIES_ONLY && owner.buddies.includes(visitor.username.toLowerCase()));
const RECYCLE_FRACTION = 0.3; // matches recyclePercentage sent at login
const FIELDS_PER_SAVED_ITEM = 17;
const REF_DEN_ITEM = "0"; // "1" would be a pet placed in the den
const REF_DEN_ITEM = "0";
const REF_PET = "1";
const PET_CATEGORY = 1; // DenItem.getInWorldId for pets (sort category 99)
const MAX_CATEGORY = 1000;
const CURRENCY_DIAMONDS = 3;
// mannequins: den items (special type 4) that stand as an animal in clothes
@@ -88,28 +91,54 @@ const readMannequin = (account, fields) => {
};
};
// DenXtCommManager.denItemsResponse: [activeDenIdx, count, ?, (invIdx, defId,
// placed, version, approved, imageId, creatorDbId, creatorUuid, [mannequin],
// denStoreInvId)...]. the three after "approved" are a masterpiece's
// where an item stands: `spots` has a place for each den it is in, by the
// den's inventory id ({cat, x, y, flip}), so one item can be in several dens
// at once. the client is only ever told about the den in use.
const spotOf = (item, den) => (item.spots ? item.spots[den] : undefined);
const isPlaced = item => Boolean(item.spots) && Object.keys(item.spots).length > 0;
const itemsInDen = account => account.denItems.filter(item => spotOf(item, account.activeDen));
// the pets standing in the owner's den in use: `inDen` is {den, x, y, flip}.
const petsInDen = account => account.pets.filter(pet => pet.inDen && pet.inDen.den === account.activeDen);
// DenXtCommManager.denItemsResponse: [activeDenIdx, count, petCount, (invIdx,
// defId, placed, version, approved, imageId, creatorDbId, creatorUuid,
// [mannequin], denStoreInvId)..., petInvIdx...]. "placed" is the category the
// den editor gave the item (DenItem.getInWorldId) in the den in use, 0 when
// it is not placed there. the three after "approved" are a masterpiece's
// (lib/masterpieces.js); one not approved yet the client keeps out of dens,
// trades and the recycler.
const sendDenItems = session => {
const {account} = session;
const {denItems} = account;
session.sendXt("di", -1, account.activeDen, denItems.length, 0,
...denItems.flatMap(item => [item.inv, item.def, item.placed ? 1 : 0, item.version, masterpieces.itemApproved(item), ...masterpieces.itemFields(item),
...mannequinOwnFields(account, item), 0]));
const pets = petsInDen(account);
session.sendXt("di", -1, account.activeDen, denItems.length, pets.length,
...denItems.flatMap(item => {
const spot = spotOf(item, account.activeDen);
return [item.inv, item.def, spot ? spot.cat || 1 : 0, item.version, masterpieces.itemApproved(item), ...masterpieces.itemFields(item),
...mannequinOwnFields(account, item), 0];
}),
...pets.map(pet => pet.inv));
};
// DenXtCommManager.denStateResponse: [itemCount, petCount, forceReload,
// (invIdx, defId, placed, x, y, version, flipped, userNameLink, imageId,
// creatorDbId, creatorUuid, [mannequin], ?)...]. forceReload makes the client finish a
// pending room change, so it is set when the den has just been entered.
// creatorDbId, creatorUuid, [mannequin], ?)..., (invIdx, lBits, uBits, eBits,
// category, x, y, flipped, createdTs, personality, toy, food, name)...].
// forceReload makes the client finish a pending room change, so it is set
// when the den has just been entered.
const sendDenState = (session, room, forceReload = true) => {
const placed = room.denOwner.denItems.filter(item => item.placed && item.den === room.denOwner.activeDen && masterpieces.itemApproved(item));
session.sendXt("ds", room.id, placed.length, 0, forceReload ? 1 : 0,
...placed.flatMap(item => [item.inv, item.def, 1, item.x, item.y, item.version, item.flip, "", ...masterpieces.itemFields(item),
...mannequinShownFields(room.denOwner, item), 0]));
const owner = room.denOwner;
const placed = itemsInDen(owner).filter(item => masterpieces.itemApproved(item));
const pets = petsInDen(owner);
session.sendXt("ds", room.id, placed.length, pets.length, forceReload ? 1 : 0,
...placed.flatMap(item => {
const spot = spotOf(item, owner.activeDen);
return [item.inv, item.def, 1, spot.x, spot.y, item.version, spot.flip, "", ...masterpieces.itemFields(item),
...mannequinShownFields(owner, item), 0];
}),
...pets.flatMap(pet => [pet.inv, pet.lBits, pet.uBits, pet.eBits, PET_CATEGORY, pet.inDen.x, pet.inDen.y, pet.inDen.flip,
pet.createdAt, pet.personality || 0, pet.toy || 0, pet.food || 0, pet.name]));
};
// adds a den item to an account; used by purchases, prizes and the item
@@ -118,7 +147,7 @@ const giveDenItem = (account, defId, version = 0) => {
if (!hasRoom(account, "denItems")) {
return null;
}
const item = {inv: account.nextInv++, def: Number(defId), version: Number(version) || 0, placed: false, den: account.activeDen, x: 0, y: 0, flip: 0};
const item = {inv: account.nextInv++, def: Number(defId), version: Number(version) || 0, spots: {}};
account.denItems.push(item);
accounts.save();
return item;
@@ -128,13 +157,15 @@ const giveDenItem = (account, defId, version = 0) => {
// on the screens of everyone inside it (DenXtCommManager.denEmptyResponse).
const clearDen = (owner, findOnline) => {
// kept so that "!den undo" can put it back (lib/commands.js).
const placed = owner.denItems.filter(item => item.placed && item.den === owner.activeDen);
const placed = itemsInDen(owner);
if (placed.length) {
owner.denUndo = {den: owner.activeDen, items: placed.map(item => ({def: item.def, version: item.version, x: item.x, y: item.y, flip: item.flip}))};
owner.denUndo = {den: owner.activeDen, items: placed.map(item => ({def: item.def, version: item.version, ...spotOf(item, owner.activeDen)}))};
}
for (const item of owner.denItems.filter(candidate => candidate.den === owner.activeDen)) {
item.placed = false;
item.x = item.y = item.flip = 0;
for (const item of placed) {
delete item.spots[owner.activeDen];
}
for (const pet of petsInDen(owner)) {
delete pet.inDen;
}
accounts.save();
const ownerSession = findOnline(owner.username);
@@ -234,6 +265,39 @@ const handlers = ({others, findOnline}) => {
sendDenItems(session);
};
// den rooms recycled from the den switcher (DenSwitch.removeDen): never the
// den in use, nor slot 0. what stood in one goes back to the inventory,
// and a den bought for gems gives back the share den items do. the reply
// is the same as for items.
const recycleDens = (session, invList) => {
const {account} = session;
const recycled = [];
for (const invIdx of new Set(String(invList).split(",", MAX_DENS).map(Number))) {
const den = account.dens.find(candidate => candidate.inv === invIdx);
if (!den || den.inv === 0 || den.inv === account.activeDen || account.dens.length <= 1) {
continue;
}
account.dens.splice(account.dens.indexOf(den), 1);
for (const item of account.denItems.filter(candidate => spotOf(candidate, den.inv))) {
delete item.spots[den.inv];
}
for (const pet of account.pets.filter(candidate => candidate.inDen && candidate.inDen.den === den.inv)) {
delete pet.inDen;
}
const refund = Math.floor(Number((defpacks.denRoomDef(den.def) || {}).cost || 0) * RECYCLE_FRACTION);
account.currency.gems += refund;
achievements.currencyChanged(account, "gems", refund);
recycled.push(den.inv);
}
accounts.save();
session.sendXt("dr", -1, recycled.length, account.currency.gems, ...recycled);
// the switcher empties the slot itself; the items that come back need
// the inventory's list.
if (recycled.length) {
sendDenItems(session);
}
};
return {
di(session) {
sendDenItems(session);
@@ -289,9 +353,12 @@ const handlers = ({others, findOnline}) => {
sendDenItems(session);
},
// DenXtCommManager.requestDenStateChange: [count, (refType, invIdx, placed,
// x, y, flipped, userNameLink, 10 mannequin fields)...]. the reply
// (DenEditor.onDenSaveSet) lists the inventory ids that were applied.
// DenXtCommManager.requestDenStateChange: [count, (refType, invIdx,
// category, x, y, flipped, userNameLink, 10 mannequin fields)...]. the
// category is DenItem.getInWorldId: 1 furniture, toys, plants and pets,
// 2 wall items, 3 music, the room's denCatId floors and wallpapers; 0 not
// placed. the reply (DenEditor.onDenSaveSet) lists the inventory ids
// that were applied.
ds(session, roomId, params) {
const {account} = session;
const count = Number(params[0]);
@@ -302,18 +369,40 @@ const handlers = ({others, findOnline}) => {
const applied = [];
const byInv = new Map(account.denItems.map(candidate => [candidate.inv, candidate]));
const mannequins = account.denItems.filter(candidate => candidate.mannequin);
const activePet = activeAvatar(account).petInvId;
for (let i = 0; i < count; i++) {
const [refType, invIdx, placed, x, y, flip, , ...outfit] = params.slice(1 + i * FIELDS_PER_SAVED_ITEM, 1 + (i + 1) * FIELDS_PER_SAVED_ITEM);
const item = byInv.get(Number(invIdx));
if (refType !== REF_DEN_ITEM || !item || ![x, y, flip].every(value => Number.isInteger(Number(value)))
|| (placed === "1" && !masterpieces.itemApproved(item))) {
const [refType, invIdx, category, x, y, flip, , ...outfit] = params.slice(1 + i * FIELDS_PER_SAVED_ITEM, 1 + (i + 1) * FIELDS_PER_SAVED_ITEM);
const cat = Number(category);
if (![x, y, flip].every(value => Number.isInteger(Number(value))) || !Number.isInteger(cat) || Math.abs(cat) > MAX_CATEGORY) {
continue;
}
item.placed = placed === "1";
item.den = account.activeDen;
item.x = item.placed ? Number(x) : 0;
item.y = item.placed ? Number(y) : 0;
item.flip = item.placed ? Number(flip) : 0;
const placed = cat !== 0;
if (refType === REF_PET) {
// the pet that follows its owner about is not put down (DenEditor says so).
const pet = account.pets.find(candidate => candidate.inv === Number(invIdx));
if (pet && !(placed && pet.inv === activePet)) {
if (placed) {
pet.inDen = {den: account.activeDen, x: Number(x), y: Number(y), flip: Number(flip)};
}
else if (pet.inDen && pet.inDen.den === account.activeDen) {
delete pet.inDen;
}
applied.push(pet.inv);
}
continue;
}
const item = byInv.get(Number(invIdx));
if (refType !== REF_DEN_ITEM || !item || (placed && !masterpieces.itemApproved(item))) {
continue;
}
// only the den in use changes: the item stays wherever else it stands.
item.spots = item.spots || {};
if (placed) {
item.spots[account.activeDen] = {cat, x: Number(x), y: Number(y), flip: Number(flip)};
}
else {
delete item.spots[account.activeDen];
}
const mannequin = isMannequin(item) && readMannequin(account, outfit);
if (mannequin) {
// A piece of clothing is on one mannequin at a time.
@@ -344,6 +433,10 @@ const handlers = ({others, findOnline}) => {
// recycleDiCallback) before it lets go of its spinner.
dr(session, roomId, [kind, invList]) {
const {account} = session;
if (kind === "-1") {
recycleDens(session, invList);
return;
}
const recycled = [];
for (const invIdx of kind === "0" ? new Set(String(invList).split(",", MAX_RECYCLED_AT_ONCE).map(Number)) : []) {
const index = account.denItems.findIndex(item => item.inv === invIdx);
@@ -396,6 +489,8 @@ const handlers = ({others, findOnline}) => {
accounts.save();
const avatar = activeAvatar(account);
session.sendXt("dc", -1, den.def, avatar.perUserAvId, avatar.petInvId);
// what is free and what is placed differs from den to den.
sendDenItems(session);
if (inOwnDen(session)) {
const {room} = session;
Object.assign(room, denRoom(account));
@@ -431,4 +526,4 @@ const handlers = ({others, findOnline}) => {
};
};
module.exports = {handlers, sendDenState, sendDenItems, sendRoomProperties, giveDenItem, clearDen, denRoom, canEnter, DEF_DEN_ROOM};
module.exports = {handlers, sendDenState, sendDenItems, sendRoomProperties, giveDenItem, clearDen, denRoom, canEnter, spotOf, isPlaced, DEF_DEN_ROOM};
+9 -1
View File
@@ -73,6 +73,14 @@ module.exports = ({findOnline, blocks}) => {
// kept by the name on them.
const senderOf = card => (card.fromId ? accounts.byId(card.fromId) : accounts.byName(card.from));
// the card's gift id: for clothing the id of its picture (ECardInbox hands
// it to SimpleIcon as an accId, which is the def's layerDefId), for the
// rest the def id or the amount.
const giftId = gift => {
const def = gift.type === TYPE_CLOTHING && defpacks.itemDef(gift.def);
return def ? Number(def.layerDefId) : gift.def;
};
// the 17 fields ECard.init takes, for one card. A secret valentine's
// sender is known here (reports about it reach them) but not sent.
const fields = card => {
@@ -81,7 +89,7 @@ module.exports = ({findOnline, blocks}) => {
const name = card.secret ? "" : senderType === FROM_HQ ? HQ_NAME_STRING : card.hq ? HQ_NAME : card.from;
return [
card.id, name, card.card, card.stamp, card.read ? 1 : 0, card.msg, card.gift ? card.gift.type : TYPE_PLAIN,
card.gift ? card.gift.def : 0, card.gift ? card.gift.color : 0, card.gift ? card.gift.name : 0,
card.gift ? giftId(card.gift) : 0, card.gift ? card.gift.color : 0, card.gift ? card.gift.name : 0,
card.hq || card.secret ? MEMBER : sender ? sender.accountType : 0,
0, // name bar data
0, // secondary type
+7
View File
@@ -142,6 +142,8 @@ const profile = (account, from) => {
lastSeen: account.lastSeen || account.lastLogin || null,
online: Boolean(world.findOnline(account.username)),
logins: account.numLogins || 0,
playtime: account.playtime,
playtimePublic: account.playtimePublic,
animals: account.avatars.length,
animalType: avatar ? avatar.type : null,
items: account.items.length,
@@ -362,6 +364,11 @@ const act = (account, body, req, from, res) => {
accounts.save();
return {ok: bio ? "Saved." : "Removed."};
}
// whether their card in the game shows how long they have played.
case "playtimePublic":
account.playtimePublic = body.on === true;
accounts.save();
return {ok: account.playtimePublic ? "Others can see your playtime on your card." : "Your playtime is private."};
// their Discord username, for their card in the game. empty takes it off.
case "discord": {
const name = badges.discordName(body.name);
+35 -7
View File
@@ -14,6 +14,7 @@ const masterpieces = require("./masterpieces.js");
const modlog = require("./modlog.js");
const reports = require("./reports.js");
const staff = require("./staff.js");
const stats = require("./stats.js");
const support = require("./support.js");
const totp = require("./totp.js");
const world = require("./world.js");
@@ -28,10 +29,13 @@ const world = require("./world.js");
// cannot sign in at all, and a trusted device is not taken for a code.
// being a moderator gives the account nothing in the game itself.
//
// what it does not give: addresses, sign-in histories, the server's log,
// what an account owns, passwords, renaming, deleting, gifts. an address
// can be banned through its player (the one they last signed in from) and
// shows here with its end left out. another moderator cannot be acted on.
// what it does not give: sign-in histories, the server's log, what an
// account owns, passwords, renaming, deleting, gifts. a moderator may look
// up which players signed in from an address they already have (a search
// written down under their name, below), but is shown no others; an
// address can be banned through its player (the one they last signed in
// from) and shows here with its end left out. another moderator cannot be
// acted on.
// everything done here is written down (lib/modlog.js) under the
// moderator's name, for the admin panel.
@@ -46,6 +50,7 @@ const failuresByAddress = limits.limiter(config.failedLoginsPerTenMinutes, TEN_M
const actionsPerTenMinutes = limits.limiter(300, TEN_MINUTES_MS); // per moderator
const sessions = new Map(); // SHA-256 of a session token -> {id: account id, expiry: ms}
const addressSearched = new Map(); // moderator's account id -> the address they last searched for
const sha256 = text => crypto.createHash("sha256").update(text).digest("hex");
@@ -91,6 +96,7 @@ const playerRow = (account, playing) => {
silenced: world.moderation.silenceRemaining(account),
nameRejected: Boolean(account.nameRejected),
moderator: Boolean(account.moderator),
playtime: account.playtime,
bio: account.bio,
discord: account.discord,
};
@@ -230,7 +236,7 @@ const handle = async (req, res, url, from, web) => {
const route = `${req.method} ${url.pathname.replace(/\/$/, "") || "/mod"}`;
if (route === "GET /mod") {
web.send(res, 200, captcha.withScriptVersion(await fs.promises.readFile(path.join(config.publicDir, "mod.html"))), "text/html; charset=utf-8");
web.send(res, 200, captcha.withScriptVersion(await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "mod.html")))), "text/html; charset=utf-8");
return;
}
if (req.method === "POST" && !limits.originAllowed(req)) {
@@ -333,8 +339,30 @@ const handle = async (req, res, url, from, web) => {
paintings: masterpieces.list(masterpieces.PENDING).length});
return;
case "GET /mod/api/players":
reply(200, {players: findPlayers(url.searchParams.get("q"))});
case "GET /mod/api/players": {
if (url.searchParams.get("by") !== "address") {
reply(200, {players: findPlayers(url.searchParams.get("q"))});
return;
}
// by address: only the address typed, which is written down (once
// for each address, though the page asks again every few seconds).
const query = String(url.searchParams.get("q") || "").trim().toLowerCase();
const found = staff.byAddress(query);
if (found.error) {
reply(400, found);
return;
}
if (addressSearched.get(mod.id) !== query) {
addressSearched.set(mod.id, query);
modlog.record(mod.username, "searched by address", "", `${query} · ${found.players.length} found`);
}
const online = playing();
reply(200, {players: found.players.map(entry => ({...playerRow(accounts.byName(entry.username), online), matchedAt: entry.lastAt}))});
return;
}
case "GET /mod/api/stats":
reply(200, stats.report(Number(url.searchParams.get("days")), Number(url.searchParams.get("offset"))));
return;
case "GET /mod/api/player": {
+13 -3
View File
@@ -12,10 +12,13 @@ const config = require("../config.js");
// the admin panel). the lists are files, read again when they change:
// lib/reserved-names.txt staff-like names
// public/filter/level1.txt the chat filter's first level: slurs, threats
// lib/sexual-names.txt sexual words, refused anywhere in a name
// (bar the short ones marked "=", see the file)
// and the names of the Epic Dens, which are how a showcase den is asked for.
const RESERVED_FILE = path.join(__dirname, "reserved-names.txt");
const SLURS_FILE = path.join(config.publicDir, "filter", "level1.txt");
const SEXUAL_FILE = path.join(__dirname, "sexual-names.txt");
const DIGITS = {0: "o", 1: "i", 3: "e", 4: "a", 5: "s", 7: "t"};
// A word as it is compared: small letters, digits at either end dropped
@@ -28,7 +31,9 @@ const plain = word => word.toLowerCase().replace(/^\d+|\d+$/g, "").replace(/\d/g
const squash = word => word.replace(/(.)\1+/g, "$1");
const stretched = word => /(.)\1\1/.test(word);
// the entries of a list file: [{text, prefix}], text made plain as above.
// the entries of a list file: [{text, prefix, word}], text made plain as
// above. "word" is for a line marked "=": in lib/sexual-names.txt the rest
// are matched anywhere in a name.
const lists = new Map(); // file -> {mtime, entries}
const read = file => {
let mtime = 0;
@@ -43,7 +48,8 @@ const read = file => {
return kept.entries;
}
const entries = fs.readFileSync(file, "utf8").split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith("#"))
.map(line => ({text: line.replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*")})).filter(entry => entry.text.length >= 2);
.map(line => ({text: line.replace(/^=/, "").replace(/\*$/, "").split(/\s+/).map(plain).join(""), prefix: line.endsWith("*"), word: line.startsWith("=")}))
.filter(entry => entry.text.length >= 2);
lists.set(file, {mtime, entries});
return entries;
};
@@ -71,7 +77,11 @@ const refused = username => {
const same = (word, entry) => word === entry.text || (entry.prefix && word.startsWith(entry.text))
|| (stretched(word) && (squash(word) === squash(entry.text) || (entry.prefix && squash(word).startsWith(squash(entry.text)))));
const hit = entry => same(whole, entry) || words.some(word => same(word, entry));
return read(RESERVED_FILE).some(hit) || read(SLURS_FILE).some(hit) || denNames().includes(whole);
// anywhere in the name, with a letter drawn out three times or more read
// as two and as one ("booooobs"; "Bobbby" is not "boob").
const drawnOut = [whole, whole.replace(/(.)\1{2,}/g, "$1$1"), whole.replace(/(.)\1{2,}/g, "$1")];
const inside = entry => (entry.word ? hit(entry) : drawnOut.some(form => form.includes(entry.text)));
return read(RESERVED_FILE).some(hit) || read(SLURS_FILE).some(hit) || read(SEXUAL_FILE).some(inside) || denNames().includes(whole);
};
module.exports = {refused, plain};
+16 -1
View File
@@ -19,6 +19,7 @@ const modpanel = require("./modpanel.js");
const erase = require("./erase.js");
const reports = require("./reports.js");
const sales = require("./sales.js");
const stats = require("./stats.js");
const staff = require("./staff.js");
const support = require("./support.js");
const totp = require("./totp.js");
@@ -140,6 +141,8 @@ const accountRow = (account, playing) => {
badges: account.badges,
featuresOff: accounts.FEATURES.filter(name => !accounts.featureOn(account, name)),
logins: account.numLogins,
playtime: account.playtime,
playtimePublic: account.playtimePublic,
online: playing.has(account.username),
room: playing.get(account.username) || null,
// seconds left, -1 for permanent, 0 for not banned
@@ -563,7 +566,7 @@ const handle = async (req, res, url, from, web) => {
const route = `${req.method} ${url.pathname.replace(/\/$/, "") || "/admin"}`;
if (route === "GET /admin") {
web.send(res, 200, await fs.promises.readFile(path.join(config.publicDir, "admin.html")), "text/html; charset=utf-8");
web.send(res, 200, await stats.withView(await fs.promises.readFile(path.join(config.publicDir, "admin.html"))), "text/html; charset=utf-8");
return;
}
if (req.method === "POST" && !sameOrigin(req)) {
@@ -646,6 +649,18 @@ const handle = async (req, res, url, from, web) => {
return;
}
// the graphs (lib/stats.js): the last `days` days, by the viewer's clock.
case "GET /admin/api/stats":
reply(200, stats.report(Number(url.searchParams.get("days")), Number(url.searchParams.get("offset"))));
return;
// who signed in from an address, or from addresses starting so.
case "GET /admin/api/address-search": {
const found = staff.byAddress(url.searchParams.get("q"));
reply(found.error ? 400 : 200, found);
return;
}
case "GET /admin/api/logs": {
const lines = log.recent(Number(url.searchParams.get("after")) || 0, (url.searchParams.get("filter") || "").slice(0, 100));
reply(200, {lines, newest: log.count()});
+59
View File
@@ -0,0 +1,59 @@
porn
boob
dick
penis
vagina
pussy
clit
cunt
dildo
vibrator
hentai
horny
slut
whore
milf
blowjob
handjob
orgasm
orgy
fetish
bdsm
nsfw
onlyfans
nude
naked
nipple
erotic
semen
sperm
jizz
titty
titties
tits
boner
sexy
ejaculat
masturbat
condom
genital
testicle
scrotum
=sex*
=cock
=cocks
=cum*
=anal
=anus
=ass
=asses
=butt
=butts
=xxx
=thot
=tit
=rape*
=rapist
=pedo*
=loli
=shota
+29 -1
View File
@@ -25,6 +25,34 @@ const disciplined = () => accounts.all()
.filter(entry => entry.banned !== 0 || entry.silenced !== 0)
.sort((a, b) => a.username.localeCompare(b.username));
// the accounts that signed in from an address, or from any address that
// starts with what was typed ("203.0.113." for the lot): from the sign-in
// histories, which hold the last 90 days (lib/accounts.js). failed tries
// are left out, being anyone's. returns {error} or {players: [{username,
// online, addresses: [{address, at}], lastAt}]}, the latest first.
const MIN_ADDRESS_QUERY = 3;
const MAX_ADDRESS_FOUND = 100;
const byAddress = query => {
const wanted = String(query || "").trim().toLowerCase().replace(/^::ffff:/, "").slice(0, 60);
if (wanted.length < MIN_ADDRESS_QUERY || !/^[0-9a-f.:]+$/.test(wanted) || !/[.:]/.test(wanted)) {
return {error: "Type at least the start of an IP address, like 203.0.113."};
}
const players = [];
for (const account of accounts.all()) {
const seen = new Map();
for (const login of account.logins) {
if (login.ok && login.address && login.address.toLowerCase().startsWith(wanted)) {
seen.set(login.address, Math.max(seen.get(login.address) || 0, login.at));
}
}
if (seen.size > 0) {
const addresses = [...seen].map(([address, at]) => ({address, at})).sort((one, other) => other.at - one.at);
players.push({username: account.username, online: Boolean(world.findOnline(account.username)), addresses, lastAt: addresses[0].at});
}
}
return {players: players.sort((one, other) => other.lastAt - one.lastAt).slice(0, MAX_ADDRESS_FOUND)};
};
const ADDRESS_ERRORS = {
not_an_address: "Not an IP address.",
own_address: "That is this machine's own address: with a proxy or a tunnel in front, everyone's.",
@@ -94,4 +122,4 @@ const answerNameRequest = (id, approve) => {
return {ok: `${oldName} is now called ${account.username}. They log in with the new name and the same password.`, username: account.username};
};
module.exports = {disciplined, banAddress, appealsFor, answerAppeal, answerNameRequest};
module.exports = {disciplined, byAddress, banAddress, appealsFor, answerAppeal, answerNameRequest};
+209
View File
@@ -0,0 +1,209 @@
"use strict";
const fs = require("fs");
const path = require("path");
const accounts = require("./accounts.js");
const config = require("../config.js");
// the game's numbers over time, for the graphs on the admin and moderator
// panels: how many were playing (a sample a minute, written as one row per
// five minutes with its average and its most), every login to the game, and
// every stretch of play when it ends. the logins and the stretches name the
// account, so they go after a year (as the privacy policy says of the
// records kept about players); the head-counts name nobody and stay.
const DAY_SECONDS = 86400;
const SAMPLE_MS = 60000;
const ROW_SECONDS = 300;
const KEPT_DAYS = 365;
const RANGES = [1, 7, 30, 90, 365]; // days a graph can cover
const TOP_PLAYERS = 10;
const SCHEMA = `
CREATE TABLE IF NOT EXISTS stats_online (at INTEGER PRIMARY KEY, average REAL NOT NULL, most INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS stats_logins (at INTEGER NOT NULL, account_id INTEGER NOT NULL, first INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS stats_logins_at ON stats_logins (at);
CREATE TABLE IF NOT EXISTS stats_sessions (ended INTEGER NOT NULL, account_id INTEGER NOT NULL, seconds INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS stats_sessions_ended ON stats_sessions (ended);
`;
const now = () => Math.floor(Date.now() / 1000);
const db = () => accounts.database();
let countOnline = () => 0;
let row = null; // the five minutes being counted: {at, sum, samples, most}
const writeRow = () => {
if (row && row.samples > 0) {
db().prepare("INSERT INTO stats_online (at, average, most) VALUES (?, ?, ?) ON CONFLICT(at) DO UPDATE SET average = excluded.average, most = excluded.most")
.run(row.at, row.sum / row.samples, row.most);
}
};
const sample = () => {
const count = countOnline();
const at = Math.floor(now() / ROW_SECONDS) * ROW_SECONDS;
if (row && row.at !== at) {
writeRow();
row = null;
}
row = row || {at, sum: 0, samples: 0, most: 0};
row.sum += count;
row.samples++;
row.most = Math.max(row.most, count);
};
const prune = () => {
const before = now() - KEPT_DAYS * DAY_SECONDS;
db().prepare("DELETE FROM stats_logins WHERE at < ?").run(before);
db().prepare("DELETE FROM stats_sessions WHERE ended < ?").run(before);
};
// `online` counts the players in the game now (lib/world.js).
const load = online => {
db().exec(SCHEMA);
countOnline = online;
prune();
sample();
setInterval(() => {
try {
sample();
}
catch (err) {
console.error(`[stats] could not count: ${err.message}`);
}
}, SAMPLE_MS).unref();
setInterval(prune, DAY_SECONDS * 1000).unref();
};
// the row being counted is written before the server stops (server.js).
const flush = () => {
try {
writeRow();
}
catch (err) {
// the database is closing
}
};
const login = (account, first) => {
db().prepare("INSERT INTO stats_logins (at, account_id, first) VALUES (?, ?, ?)").run(now(), account.id, first ? 1 : 0);
};
const session = (account, seconds) => {
if (seconds > 0) {
db().prepare("INSERT INTO stats_sessions (ended, account_id, seconds) VALUES (?, ?, ?)").run(now(), account.id, Math.round(seconds));
}
};
// the numbers for the last `days` days, in buckets of an hour (a day or
// two) or of a day, the days as the viewer's clock has them: `offset` is
// their minutes ahead of UTC. the hours of the day and the days of the week
// are theirs too.
const report = (days, offset) => {
days = RANGES.includes(days) ? days : 7;
offset = Number.isInteger(offset) && Math.abs(offset) <= 14 * 60 ? offset * 60 : 0;
const end = now();
const start = end - days * DAY_SECONDS;
const size = days <= 2 ? 3600 : DAY_SECONDS;
// the bucket a moment falls in, by the viewer's clock.
const bucketOf = at => Math.floor((at + offset) / size) * size - offset;
const first = bucketOf(start);
const buckets = new Map();
for (let at = first; at <= end; at += size) {
buckets.set(at, {at, average: 0, most: 0, logins: 0, players: 0, newAccounts: 0, samples: 0, sum: 0, who: new Set()});
}
const hours = Array.from({length: 24}, () => ({sum: 0, samples: 0, logins: 0}));
const week = Array.from({length: 7}, () => Array.from({length: 24}, () => ({sum: 0, samples: 0})));
const local = at => new Date((at + offset) * 1000);
let most = {count: 0, at: null};
for (const sampled of db().prepare("SELECT at, average, most FROM stats_online WHERE at >= ? ORDER BY at").all(start)) {
const bucket = buckets.get(bucketOf(sampled.at));
if (bucket) {
bucket.sum += sampled.average;
bucket.samples++;
bucket.most = Math.max(bucket.most, sampled.most);
}
const when = local(sampled.at);
hours[when.getUTCHours()].sum += sampled.average;
hours[when.getUTCHours()].samples++;
week[when.getUTCDay()][when.getUTCHours()].sum += sampled.average;
week[when.getUTCDay()][when.getUTCHours()].samples++;
if (sampled.most > most.count) {
most = {count: sampled.most, at: sampled.at};
}
}
if (row && row.at >= start && row.most > most.count) {
most = {count: row.most, at: row.at};
}
const everyone = new Set();
let logins = 0;
let firstLogins = 0;
for (const entry of db().prepare("SELECT at, account_id, first FROM stats_logins WHERE at >= ?").all(start)) {
const bucket = buckets.get(bucketOf(entry.at));
if (bucket) {
bucket.logins++;
bucket.who.add(entry.account_id);
}
hours[local(entry.at).getUTCHours()].logins++;
everyone.add(entry.account_id);
logins++;
firstLogins += entry.first;
}
const all = accounts.all();
let newAccounts = 0;
for (const account of all) {
if (account.createdAt >= start) {
newAccounts++;
const bucket = buckets.get(bucketOf(account.createdAt));
if (bucket) {
bucket.newAccounts++;
}
}
}
const played = db().prepare("SELECT COUNT(*) AS count, COALESCE(SUM(seconds), 0) AS total FROM stats_sessions WHERE ended >= ?").get(start);
const ever = db().prepare("SELECT at, most FROM stats_online ORDER BY most DESC, at DESC LIMIT 1").get();
return {
days,
bucketSeconds: size,
summary: {
online: countOnline(),
accounts: all.length,
newAccounts,
logins,
players: everyone.size,
firstLogins,
peak: most,
peakEver: ever && (!row || ever.most >= row.most) ? {count: ever.most, at: ever.at} : row ? {count: row.most, at: row.at} : {count: 0, at: null},
sessions: played.count,
averageSessionSeconds: played.count ? Math.round(played.total / played.count) : 0,
playedSeconds: played.total,
},
series: [...buckets.values()].map(bucket => ({
at: bucket.at,
average: bucket.samples ? Math.round(bucket.sum / bucket.samples * 10) / 10 : null,
most: bucket.samples ? bucket.most : null,
logins: bucket.logins,
players: bucket.who.size,
newAccounts: bucket.newAccounts,
})),
hours: hours.map(hour => ({average: hour.samples ? Math.round(hour.sum / hour.samples * 10) / 10 : null, logins: hour.logins})),
week: week.map(day => day.map(hour => (hour.samples ? Math.round(hour.sum / hour.samples * 10) / 10 : null))),
topPlaytime: all.filter(account => account.playtime > 0).sort((one, other) => other.playtime - one.playtime).slice(0, TOP_PLAYERS)
.map(account => ({username: account.username, seconds: account.playtime})),
};
};
// A panel's page with the Stats tab (public/stats-view.html) where it says
// <!--stats-view-->: the admin and the moderator panels show the same one.
const withView = async page => {
const view = await fs.promises.readFile(path.join(config.publicDir, "stats-view.html"), "utf8");
return Buffer.from(String(page).replace("<!--stats-view-->", () => view));
};
module.exports = {load, flush, login, session, report, withView, RANGES};
+7 -3
View File
@@ -91,7 +91,8 @@ module.exports = ({findOnline, blocks}) => {
return [DONE_CLOTHING, entry.def, entry.inv, entry.color];
}
if (type === TYPE_DEN_ITEM) {
return [DONE_DEN_ITEM, entry.def, entry.inv, entry.version, "true", ...masterpieces.itemFields(entry)];
// the inventory id first here, unlike clothing (TradeManager.displayTradeDone).
return [DONE_DEN_ITEM, entry.inv, entry.def, entry.version, "true", ...masterpieces.itemFields(entry)];
}
return [DONE_PET, entry.createdAt, entry.inv, entry.lBits & 0xFF, entry.lBits, entry.uBits, entry.eBits, 0, 0, 0, entry.name];
};
@@ -154,8 +155,11 @@ module.exports = ({findOnline, blocks}) => {
if (type === TYPE_CLOTHING) {
moved.on = [];
}
else if (type === TYPE_PET) {
delete moved.inDen; // it was standing in the giver's den
}
else if (type === TYPE_DEN_ITEM) {
Object.assign(moved, {placed: false, x: 0, y: 0, flip: 0});
moved.spots = {}; // it stood in the giver's dens
delete moved.mannequin; // a mannequin changes hands bare
}
collectionOf(to, type).push(moved);
@@ -346,7 +350,7 @@ module.exports = ({findOnline, blocks}) => {
const offers = {
// what `account` could give: its clothing and den items, by name.
owned: account => [TYPE_CLOTHING, TYPE_DEN_ITEM].flatMap(type => collectionOf(account, type)
.filter(entry => type !== TYPE_DEN_ITEM || (masterpieces.itemApproved(entry) && !entry.placed))
.filter(entry => type !== TYPE_DEN_ITEM || (masterpieces.itemApproved(entry) && Object.keys(entry.spots || {}).length === 0))
.map(entry => ({type, inv: entry.inv, name: nameOf(type, entry)})))
.sort((one, other) => one.name.localeCompare(other.name)),
+93 -20
View File
@@ -32,6 +32,7 @@ const tradeHandlers = require("./trades.js");
const stubHandlers = require("./stubs.js");
const wallModule = require("./walls.js");
const worldItems = require("./worlditems.js");
const stats = require("./stats.js");
const {CURRENCIES, DIAMOND_TYPES, activeAvatar, avatarById, activePet, equippedBits, wornItems, lastSeenField} = require("./player.js");
// game logic behind the socket. field orders below mirror the client's
@@ -86,6 +87,9 @@ const USER_VAR_DEN_TUTORIAL = 379;
const USER_VAR_TRADE_TUTORIAL = 129;
const TUTORIALS_ALL_SEEN = 65535;
const BIT_FLAG_VARS = [USER_VAR_DEN_TUTORIAL, USER_VAR_TRADE_TUTORIAL];
// the settings menu's switches, a bit each (gui.MySettings): the client sends
// the bit's number and 1 to set it or 0 to clear it. unset is -1, every bit clear.
const USER_VAR_SETTINGS = 363;
const GEM_BONUS_NEVER_DUE = 65535;
// pets the pet picker must not offer (PetCreator.onNotViewablePetDefsLoaded); none here.
const GENERIC_LIST_HIDDEN_PETS = 574;
@@ -276,7 +280,11 @@ const login = (session, msg) => {
leaveWorld(existing);
}
session.account = account;
accounts.hold(account);
account.numLogins++;
session.playingSince = Date.now();
session.playStarted = Date.now();
stats.login(account, account.numLogins === 1);
accounts.recordLogin(account, "game", session.address);
account.lastLogin = Math.floor(Date.now() / 1000);
session.recentChat = [];
@@ -440,6 +448,27 @@ const sendUserVars = session => {
const findOnline = username => online.get(String(username).toLowerCase());
// a custom colour (lib/colours.js) for these four RGB values, made if it is
// new and the account has not made its day's worth; everyone online is told
// of a new one before anybody can be given it, and `asker` (a session) of an
// old one. returns what colours.allocate does.
const makeColour = (account, rgbs, asker = null) => {
const today = Math.floor(Date.now() / 86400000);
const made = account.coloursMade && account.coloursMade.day === today ? account.coloursMade.count : 0;
const entry = colours.allocate(rgbs, made < config.customColoursPerDay);
if (!entry || entry.full) {
return entry;
}
if (entry.created) {
account.coloursMade = {day: today, count: made + 1};
accounts.save();
}
for (const recipient of entry.created ? online.values() : asker ? [asker] : []) {
recipient.sendXt("xcc", -1, 1, entry.id, ...entry.rgbs);
}
return entry;
};
// the account's chat filter, for its game to apply: [chosen, level, mode, own words].
const sendFilter = session => {
const {filter} = session.account;
@@ -478,23 +507,9 @@ const handlers = {
// A colour somebody made before is anybody's to use; a new one counts
// against the day's allowance of whoever asks (config.customColoursPerDay).
xcc(session, roomId, params) {
const {account} = session;
const today = Math.floor(Date.now() / 86400000);
const made = account.coloursMade && account.coloursMade.day === today ? account.coloursMade.count : 0;
const entry = colours.allocate(params.slice(0, 4).map(Number), made < config.customColoursPerDay);
if (!entry) {
return;
}
if (entry.full) {
const entry = makeColour(session.account, params.slice(0, 4).map(Number), session);
if (entry && entry.full) {
tell(session, "No more new colours today. Colours made before can still be used.");
return;
}
if (entry.created) {
account.coloursMade = {day: today, count: made + 1};
accounts.save();
}
for (const recipient of entry.created ? online.values() : [session]) {
recipient.sendXt("xcc", -1, 1, entry.id, ...entry.rgbs);
}
},
@@ -714,7 +729,7 @@ const handlers = {
// AchievementXtCommManager.requestSetUserVar: [varId, value, ?]. the reply
// (setUserVarResponse) is [varId, value, newAchievementCount].
zs(session, roomId, [id, value]) {
zs(session, roomId, [id, value, set]) {
if (!/^\d{1,4}$/.test(id) || !Number.isFinite(Number(value))) {
return;
}
@@ -731,6 +746,14 @@ const handlers = {
else if (BIT_FLAG_VARS.includes(Number(id))) {
vars[id] = TUTORIALS_ALL_SEEN;
}
else if (Number(id) === USER_VAR_SETTINGS) {
const bit = Number(value);
if (!Number.isInteger(bit) || bit < 0 || bit > 30) {
return;
}
const bits = Math.max(0, Number(vars[id]) || 0);
vars[id] = set === "0" ? bits & ~(1 << bit) : bits | (1 << bit);
}
else if (achievements.counts(id)) {
// A var that achievements count in: the games report "one more" as 1
// and a best score as the score, and the official server knew which
@@ -818,7 +841,7 @@ const handlers = {
// the icons after the name, and their bio, for the Bio tab
// (lib/badges.js).
session.sendXt("xbn", -1, account.username, moderation.banRemaining(account), account.createdAt,
account.discord, badges.cardField(account), account.bio);
account.discord, badges.cardField(account), cardBio(account));
}
},
@@ -931,6 +954,46 @@ const leaveRoom = session => {
}
};
// the Bio tab's words: the bio, under the time played when the player
// shows it (their account page). the card makes the words smaller to fit.
const playedText = seconds => {
const hours = Math.floor(seconds / 3600);
if (hours >= 1) {
return `Played ${hours.toLocaleString("en-US")} hour${hours === 1 ? "" : "s"}`;
}
const minutes = Math.floor(seconds / 60);
return `Played ${minutes} minute${minutes === 1 ? "" : "s"}`;
};
const cardBio = account => {
if (!account.playtimePublic) {
return account.bio;
}
const session = online.get(account.username.toLowerCase());
if (session) {
countPlaytime(session);
}
return account.bio ? `${playedText(account.playtime)}\n\n${account.bio}` : playedText(account.playtime);
};
// the time since it was last counted, added to the account's playtime.
const countPlaytime = session => {
if (session.account && session.playingSince) {
const elapsed = Date.now() - session.playingSince;
session.account.playtime += Math.floor(elapsed / 1000);
session.playingSince = Date.now() - (elapsed % 1000);
}
};
// counted every minute too, so that a server that stops without warning
// loses no more than that, and what others see is never far behind.
setInterval(() => {
for (const session of online.values()) {
countPlaytime(session);
}
if (online.size > 0) {
accounts.save();
}
}, 60000).unref();
const leaveWorld = session => {
minigames.leave(session);
trades.forget(session);
@@ -938,6 +1001,9 @@ const leaveWorld = session => {
if (session.account && online.get(session.account.username.toLowerCase()) === session) {
online.delete(session.account.username.toLowerCase());
session.account.lastSeen = Math.floor(Date.now() / 1000);
countPlaytime(session);
stats.session(session.account, (Date.now() - session.playStarted) / 1000);
accounts.release(session.account);
accounts.save();
buddies.announce(session.account);
}
@@ -1023,7 +1089,8 @@ const enterRoom = (session, name, base, displayName, shardId, props = {}) => {
if (room && room === session.room) {
return;
}
if (room && room.sessions.size >= config.maxUsersPerRoom) {
// moderators (marked so in the admin panel) are let into a full room.
if (room && room.sessions.size >= config.maxUsersPerRoom && !session.account.moderator) {
joinFailed(session, "This room is currently full");
return;
}
@@ -1151,6 +1218,11 @@ const joinRoom = (session, requested) => {
// reply says; a starting room in the flashvars it does not honour).
if (!session.arrived) {
session.arrived = true;
// the client asks for its buddy list only when a window wants it
// (BuddyList.requestBuddyListIfNeeded), and draws every name tag as a
// non-buddy's until then: it is sent ahead of the first room, as the
// client takes it unasked (BuddyManager.buddyListResponseHandler).
handlers.bl(session);
const {startInDen, startRoom, username} = session.account;
const den = startInDen ? username : /^den/i.test(startRoom || "") ? startRoom.slice(3) : null;
if (den !== null && accounts.byName(den)) {
@@ -1317,6 +1389,7 @@ module.exports = {
close: leaveWorld,
findOnline,
makeColour,
sendItemList,
setTheme,
// offers left on the account page (lib/trades.js); `refresh` shows a
@@ -1447,7 +1520,7 @@ module.exports = {
continue;
}
changed.add(account);
if (held.some(item => item.placed)) {
if (held.some(dens.isPlaced)) {
shownIn.push(rooms.get(`den${account.username}`));
}
account.denItems = account.denItems.filter(item => item.image !== painting.id);
+37
View File
@@ -338,6 +338,16 @@
<p class="status" id="bio-status" role="status"></p>
</section>
<section>
<h2>Playtime</h2>
<p id="playtime-text"></p>
<div class="switch">
<div class="what"><b>Show on my card</b><span class="hint">At the top of the Bio tab, for anyone who opens your card in the game.</span></div>
<button id="playtime-public" type="button" aria-pressed="false">Private</button>
</div>
<p class="status" id="playtime-status" role="status"></p>
</section>
<section>
<h2>Discord</h2>
<p id="badges" hidden></p>
@@ -610,6 +620,7 @@
[account.online ? "Playing now" : account.lastSeen ? when(account.lastSeen) : "Not played yet", "Last seen"],
[when(account.createdAt), "Created"],
[account.logins.toLocaleString(), "Logins"],
[played(account.playtime), "Playtime"],
[`${account.animals}${ANIMALS[account.animalType] ? ` · ${ANIMALS[account.animalType]} in use` : ""}`, "Animals"],
[account.pets.toLocaleString(), "Pets"],
[account.items.toLocaleString(), "Clothing"],
@@ -638,6 +649,12 @@
return row;
}));
$("playtime-text").textContent = `You have played for ${played(account.playtime)}.`;
$("playtime-public").textContent = account.playtimePublic ? "Public" : "Private";
$("playtime-public").setAttribute("aria-pressed", String(account.playtimePublic));
$("playtime-public").setAttribute("aria-label", `Show playtime on my card: ${account.playtimePublic ? "public" : "private"}`);
$("playtime-public").disabled = false;
if (document.activeElement !== $("bio-text")) {
$("bio-text").value = account.bio;
}
@@ -1148,6 +1165,26 @@
});
$("forget-devices").addEventListener("click", () => act({action: "forgetDevices"}, "two-step-status"));
// time played, in the largest units that say it: "3 days 4 hours".
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
const unit = (count, name) => `${count.toLocaleString()} ${name}${count === 1 ? "" : "s"}`;
if (days > 0) {
return hours > 0 ? `${unit(days, "day")} ${unit(hours, "hour")}` : unit(days, "day");
}
if (hours > 0) {
return minutes > 0 ? `${unit(hours, "hour")} ${unit(minutes, "minute")}` : unit(hours, "hour");
}
return unit(minutes, "minute");
};
$("playtime-public").addEventListener("click", async () => {
$("playtime-public").disabled = true;
await act({action: "playtimePublic", on: !account.playtimePublic}, "playtime-status");
$("playtime-public").disabled = false;
});
const bioCount = () => {
$("bio-count").textContent = `${[...$("bio-text").value.trim()].length} / ${account ? account.bioLimit : 200}`;
};
+99 -5
View File
@@ -245,6 +245,7 @@
<nav role="tablist">
<button role="tab" data-tab="overview" aria-selected="true">Overview</button>
<button role="tab" data-tab="accounts" aria-selected="false">Accounts</button>
<button role="tab" data-tab="stats" aria-selected="false">Stats</button>
<button role="tab" data-tab="reports" aria-selected="false">Reports<span id="report-count"></span></button>
<button role="tab" data-tab="support" aria-selected="false">Requests<span id="support-count"></span></button>
<button role="tab" data-tab="masterpieces" aria-selected="false">Masterpieces<span id="masterpiece-count"></span></button>
@@ -274,9 +275,17 @@
</div>
</div>
<div data-view="stats" hidden>
<!--stats-view-->
</div>
<div data-view="accounts" hidden>
<section>
<div class="toolbar">
<select id="account-search-by" aria-label="Search by">
<option value="name">By name</option>
<option value="address">By IP address</option>
</select>
<input id="account-search" type="search" placeholder="Search" aria-label="Search accounts">
<select id="account-filter" aria-label="Which accounts">
<option value="all">All</option>
@@ -284,7 +293,15 @@
<option value="banned">Banned</option>
</select>
</div>
<div class="table-wrap"><table>
<div id="address-view" hidden>
<p class="hint">Accounts that signed in from this address, or from addresses starting with it, in the last 90 days.</p>
<p class="status" id="address-status" role="status"></p>
<div class="table-wrap"><table>
<thead><tr><th>Name</th><th>State</th><th>Addresses</th><th>Last from there</th></tr></thead>
<tbody id="address-results"></tbody>
</table></div>
</div>
<div class="table-wrap" id="account-list"><table>
<thead><tr><th>Name</th><th>State</th><th>Created</th><th>Last login</th><th>Last seen</th><th class="num">Logins</th><th class="num">Animals</th><th class="num">Items</th></tr></thead>
<tbody id="accounts"></tbody>
</table></div>
@@ -744,8 +761,61 @@
return tags.length ? tags : [el("span", "Offline", "hint")];
};
// time played: "3d 4h", "2h 15m", "40m".
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
return days > 0 ? `${days.toLocaleString()}d ${hours}h` : hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
};
// by IP address: the server looks through the sign-in histories.
let addressFound = null; // {query, players} or null
const searchByAddress = async () => {
const query = $("account-search").value.trim();
if (query === "") {
addressFound = null;
setStatus($("address-status"), "");
renderAccounts();
return;
}
const result = await api(`address-search?q=${encodeURIComponent(query)}`);
if (query !== $("account-search").value.trim()) {
return; // typed on meanwhile
}
addressFound = result.ok ? {query, players: result.data.players} : null;
setStatus($("address-status"), result.ok ? (result.data.players.length ? "" : "Nobody signed in from there.") : result.data.error || "That did not work.", !result.ok);
renderAccounts();
};
const renderAddressResults = () => {
const found = addressFound ? addressFound.players : [];
$("address-results").replaceChildren(...found.map(entry => {
const account = accounts.find(one => one.username === entry.username);
const row = el("tr", undefined, entry.username === selected ? "pick selected" : "pick");
const nameCell = el("td");
const pick = el("button", entry.username);
pick.type = "button";
nameCell.append(pick);
const stateCell = el("td");
if (account) {
stateCell.append(...accountState(account).flatMap(tag => [tag, " "]));
}
row.addEventListener("click", () => select(entry.username));
row.append(nameCell, stateCell, el("td", entry.addresses.map(one => one.address).join(", ")), el("td", when(entry.lastAt)));
return row;
}));
};
const renderAccounts = () => {
const query = $("account-search").value.trim().toLowerCase();
const byAddress = $("account-search-by").value === "address";
$("address-view").hidden = !byAddress;
$("account-list").hidden = byAddress;
if (byAddress) {
renderAddressResults();
$("no-accounts").hidden = true;
}
const query = byAddress ? "" : $("account-search").value.trim().toLowerCase();
const filter = $("account-filter").value;
const shown = accounts
.filter(account => account.username.toLowerCase().includes(query))
@@ -769,11 +839,13 @@
el("td", account.items.toLocaleString(), "num"));
return row;
}));
$("no-accounts").hidden = shown.length > 0;
if (!byAddress) {
$("no-accounts").hidden = shown.length > 0;
}
const current = accounts.find(account => account.username === selected);
$("detail").hidden = !current;
if (current) {
$("detail-name").textContent = `${current.username} · ${current.gems.toLocaleString()} gems`;
$("detail-name").textContent = `${current.username} · ${current.gems.toLocaleString()} gems · played ${played(current.playtime || 0)}${current.playtimePublic ? " (public)" : ""}`;
}
};
@@ -979,7 +1051,26 @@
}
});
$("account-search").addEventListener("input", renderAccounts);
let addressWait = null;
$("account-search").addEventListener("input", () => {
if ($("account-search-by").value === "address") {
clearTimeout(addressWait);
addressWait = setTimeout(searchByAddress, 400);
}
else {
renderAccounts();
}
});
$("account-search-by").addEventListener("change", () => {
const byAddress = $("account-search-by").value === "address";
$("account-search").placeholder = byAddress ? "203.0.113.7, or the start of one" : "Search";
if (byAddress) {
searchByAddress();
}
else {
renderAccounts();
}
});
$("account-filter").addEventListener("change", renderAccounts);
const act = async (username, action, extra, statusElement) => {
@@ -1378,6 +1469,9 @@
renderAccounts();
}
}
else if (tab === "stats") {
await window.statsView.load(api);
}
else if (tab === "reports") {
result = await api(`reports?handled=${$("report-filter").value}`);
if (result.ok) {
+8
View File
@@ -76,6 +76,14 @@
window.ipc.sendToHost("fps", count);
}
// an address the SWF wants open (AJClient.finderLink): the client opens
// it in the system browser, being a webview that may open no window.
function ajOpenPage(url) {
if (/^https:\/\//.test(String(url))) {
window.ipc.sendToHost("openPage", String(url));
}
}
function ajPrint(imageData) {
window.ipc.sendToHost("printImage", imageData);
}
+52 -7
View File
@@ -261,19 +261,25 @@
<button role="tab" data-tab="requests" aria-selected="false">Requests<span id="request-count"></span></button>
<button role="tab" data-tab="masterpieces" aria-selected="false">Masterpieces<span id="masterpiece-count"></span></button>
<button role="tab" data-tab="bans" aria-selected="false">Bans</button>
<button role="tab" data-tab="stats" aria-selected="false">Stats</button>
</nav>
<div data-view="players">
<section>
<div class="toolbar">
<select id="player-search-by" aria-label="Search by">
<option value="name">By name</option>
<option value="address">By IP address</option>
</select>
<input id="player-search" type="search" placeholder="Search" aria-label="Search players">
<span class="hint" id="online-count"></span>
</div>
<div class="table-wrap"><table>
<thead><tr><th>Name</th><th>State</th><th>Where</th><th>Last seen</th></tr></thead>
<thead><tr><th>Name</th><th>State</th><th>Where</th><th id="players-when">Last seen</th></tr></thead>
<tbody id="players"></tbody>
</table></div>
<div class="empty" id="no-players" hidden>No players match.</div>
<p class="hint" id="address-hint" hidden>Players who signed in from this address, or from addresses starting with it, in the last 90 days. Each search is written in the moderator log.</p>
</section>
<section id="detail" hidden>
<h2 id="detail-name"></h2>
@@ -316,6 +322,10 @@
</section>
</div>
<div data-view="stats" hidden>
<!--stats-view-->
</div>
<div data-view="chat" hidden>
<section>
<form id="chat-form" class="toolbar">
@@ -456,6 +466,13 @@
}
return "under a minute";
};
// time played: "3d 4h", "2h 15m", "40m".
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
return days > 0 ? `${days.toLocaleString()}d ${hours}h` : hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
};
const left = seconds => (seconds === -1 ? "Until lifted" : seconds ? `${duration(seconds)} left` : "—");
let check = null; // the captcha (public/captcha.js), once the sign-in is shown
@@ -515,10 +532,12 @@
const row = el("tr", undefined, player.username === selected ? "pick selected" : "pick");
const stateCell = el("td");
stateCell.append(...stateTags(player).flatMap(tag => [tag, " "]));
row.append(el("td", player.username), stateCell, el("td", player.room || "—"), el("td", player.online ? "Now" : when(player.lastSeen)));
row.append(el("td", player.username), stateCell, el("td", player.room || "—"),
el("td", player.matchedAt ? when(player.matchedAt) : player.online ? "Now" : when(player.lastSeen)));
row.addEventListener("click", () => select(player.username === selected ? null : player.username));
return row;
}));
$("no-players").textContent = "No players match.";
$("no-players").hidden = players.length > 0;
};
@@ -546,6 +565,7 @@
["Where", player.online ? player.room : "Offline"],
["Last seen", player.online ? "Now" : when(player.lastSeen)],
["Joined", when(player.createdAt)],
["Playtime", played(player.playtime || 0)],
["Ban", player.banned === 0 ? "—" : `${left(player.banned)} · ${player.banReason}`],
["Chat", player.silenced === 0 ? "—" : `Silenced: ${left(player.silenced).toLowerCase()}`],
["Reports waiting", String(player.openReports)],
@@ -623,7 +643,16 @@
}
});
$("player-search").addEventListener("input", () => refresh());
// by address, asked once typing stops: each search is written down.
let searchWait = null;
$("player-search").addEventListener("input", () => {
clearTimeout(searchWait);
searchWait = setTimeout(refresh, $("player-search-by").value === "address" ? 700 : 0);
});
$("player-search-by").addEventListener("change", () => {
$("player-search").placeholder = $("player-search-by").value === "address" ? "203.0.113.7, or the start of one" : "Search";
refresh();
});
const chatUrl = before => `chat?username=${encodeURIComponent(chatQuery.username)}&room=${encodeURIComponent(chatQuery.room)}`
+ `&text=${encodeURIComponent(chatQuery.text)}&before=${before}`;
@@ -874,11 +903,24 @@
$("online-count").textContent = `${counts.data.online} playing`;
}
if (shown === "players") {
const result = await api(`players?q=${encodeURIComponent($("player-search").value.trim())}`);
if (result.ok) {
players = result.data.players;
const byAddress = $("player-search-by").value === "address";
const query = $("player-search").value.trim();
$("players-when").textContent = byAddress ? "Last from address" : "Last seen";
$("address-hint").hidden = !byAddress;
if (byAddress && query === "") {
players = [];
renderPlayers();
await loadDetail();
}
else {
const result = await api(`players?q=${encodeURIComponent(query)}${byAddress ? "&by=address" : ""}`);
players = result.ok ? result.data.players : [];
renderPlayers();
if (!result.ok && byAddress) {
$("no-players").textContent = said(result);
}
if (result.ok) {
await loadDetail();
}
}
}
else if (shown === "chat") {
@@ -905,6 +947,9 @@
renderMasterpieces(result.data);
}
}
else if (shown === "stats") {
await window.statsView.load(api);
}
else if (shown === "bans") {
const result = await api("bans");
if (result.ok) {
+11 -6
View File
@@ -161,7 +161,7 @@
<section>
<h2>1. Who is responsible</h2>
<p>The controller of your personal data is the operator of Burrow, {{operator}}. Contact for anything in this policy: {{legalEmail}}. General contact: {{adminEmail}}.</p>
<p>We do not sell data, show ads, track you across sites or send marketing. We do not collect your real name, email address or date of birth. The only statistics we see are the overall traffic figures described in section 4.</p>
<p>We do not sell data, show ads, track you across sites or send marketing. We do not collect your real name, email address or date of birth. The only statistics we keep are the game's own activity figures in section 2, which are used only to run and plan the server, and the overall traffic figures described in section 4.</p>
</section>
<section>
@@ -173,7 +173,9 @@
<tr><td>Your game data: animals, items, dens, pets, buddies, block list, trades, achievements, settings</td><td>To run the game for you</td></tr>
<tr><td>What you choose to write or make: bio, Discord username (optional), Jam-A-Grams, wall posts, paintings, feedback</td><td>To show or deliver it as you asked</td></tr>
<tr><td>Typed chat and whispers, with the room and time</td><td>Moderation: reviewing reports and deciding on bans</td></tr>
<tr><td>IP address at each sign-in, and sign-in times</td><td>Security: your sign-in history, limiting abuse, address bans</td></tr>
<tr><td>IP address at each sign-in, and sign-in times</td><td>Security: your sign-in history, limiting abuse, address bans, and finding accounts made to get around a ban</td></tr>
<tr><td>When you log in to the game, how long each visit lasts, and your total playtime</td><td>To show you your playtime, and for overall activity figures (how many people play and when) that staff use to run the server</td></tr>
<tr><td>The number of players online, counted every minute</td><td>Overall activity figures. This count is not linked to anyone</td></tr>
<tr><td>Reports, bans and their reasons, appeals, username rejections</td><td>Moderation and preventing ban evasion</td></tr>
<tr><td>2FA secret and trusted-device tokens, if you turn 2FA on</td><td>To protect your account</td></tr>
<tr><td>Technical error reports sent by the game client</td><td>Fixing bugs</td></tr>
@@ -185,9 +187,10 @@
<section>
<h2>3. Who can see it</h2>
<ul>
<li><b>Other players</b> see your username, animals, den, bio, Discord username if you add one, badges, when you joined and were last seen, your chat in the room you are in, and whether you are currently banned.</li>
<li><b>Moderators</b> can also read stored chat and whispers, reports, and ban history. They cannot see your IP address, sign-in history, password or inventory.</li>
<li><b>The administrator</b> can see everything listed in section 2.</li>
<li><b>Other players</b> see your username, animals, den, bio, Discord username if you add one, badges, when you joined and were last seen, your chat in the room you are in, whether you are currently banned, and your total playtime if you make it public on your account page (it is private unless you choose otherwise).</li>
<li><b>Moderators</b> can also read stored chat and whispers, reports, and ban history, and see your total playtime and the overall activity figures. They cannot see your IP address, sign-in history, password or inventory.</li>
<li><b>Moderators</b> can look up which accounts signed in from an IP address they already have, only to stop ban evasion: finding new accounts made by someone who is banned. The search shows only account names and when they signed in from that address, never the address itself or any other address. Every search is recorded under the moderator's name and reviewed by the administrator.</li>
<li><b>The administrator</b> can see everything listed in section 2, and can search accounts by IP address for the same purpose.</li>
<li><b>Our hosting provider</b> stores the data on our behalf, in {{hostedIn}}. If that is outside your country, your data is transferred there to provide the service.</li>
<li><b>Cloudflare</b> carries part of the traffic to this server. See section 4.</li>
</ul>
@@ -214,10 +217,12 @@
<tr><td>Handled reports, feedback and username requests</td><td>12 months</td></tr>
<tr><td>Ban records</td><td>While the account exists, then 12 months</td></tr>
<tr><td>Banned IP addresses</td><td>Until the ban is lifted</td></tr>
<tr><td>Record of game logins and visit lengths</td><td>12 months</td></tr>
<tr><td>Number of players online (not linked to anyone)</td><td>Kept indefinitely</td></tr>
<tr><td>Backups</td><td>14 days</td></tr>
</tbody>
</table></div>
<p style="margin-top:12px">When you delete your account we delete your game data, chat, appeal, feedback, username requests and paintings straight away. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
<p style="margin-top:12px">When you delete your account we delete your game data, chat, appeal, feedback, username requests and paintings straight away, and your total playtime. Your past logins stay in the overall activity figures for up to 12 months and are not shown to anyone by name. Your username is held for 30 days so nobody can pass as you, and ban records are kept as shown above. Copies in backups disappear within 14 days.</p>
</section>
<section>
+2 -2
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Item finder</title>
<title>Item giver</title>
<link rel="icon" type="image/png" href="/logo-square.png">
<style>
/* black and white throughout, in the game's own text font: the look of
@@ -147,7 +147,7 @@
<body>
<main>
<img class="logo" src="/logo.png" alt="">
<h1>Item finder</h1>
<h1>Item giver</h1>
<p class="lede">Search every clothing and den item by name or id and add it to an account for free. In-game shops only stock a slice of the catalogue each.</p>
<div class="controls">
+324
View File
@@ -0,0 +1,324 @@
<!-- the Stats tab of the admin panel (admin.html) and the moderator panel
(mod.html), put in each where it says so by lib/panel.js and
lib/modpanel.js. the numbers are lib/stats.js's; the graphs are drawn
here, in white on black like the rest. hovering a bar or a point
names its numbers. -->
<style>
.stats-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px; margin-bottom: 16px; }
.stats-tile { padding: 12px 14px 11px; border: 1px solid var(--line); border-radius: 18px; min-width: 0; }
.stats-tile .value { font-size: 24px; font-weight: 700; line-height: 1.15; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.stats-tile .name { margin-top: 2px; font-size: 11px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--muted); }
.stats-tile .sub { font-size: 12px; color: var(--muted); }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 16px; }
.stats-grid section { margin: 0; min-width: 0; }
.stats-chart { width: 100%; height: auto; display: block; }
.stats-chart text { fill: var(--muted); font: 11px "DigitalDelivery", system-ui, sans-serif; }
.stats-chart .axis { stroke: var(--line); stroke-width: 1; }
.stats-chart .bar { fill: var(--text); }
.stats-chart .bar.dim { fill: #555; }
.stats-chart .hit { fill: transparent; }
.stats-chart .hit:hover + .bar, .stats-chart .bar:hover { fill: #bbb; }
.stats-chart .line { fill: none; stroke: var(--text); stroke-width: 2; }
.stats-chart .line.dim { stroke: #666; stroke-width: 1.5; stroke-dasharray: 4 3; }
.stats-legend { display: flex; gap: 14px; flex-wrap: wrap; font-size: 12px; color: var(--muted); margin: 0 0 8px; }
.stats-legend span::before { content: ""; display: inline-block; width: 14px; height: 0; border-top: 2px solid var(--text); vertical-align: middle; margin-right: 6px; }
.stats-legend span.dim::before { border-top: 2px dashed #666; }
.stats-legend span.box::before { height: 10px; border: 0; background: var(--text); }
.stats-legend span.box.dim::before { background: #555; }
.stats-heat { display: grid; grid-template-columns: 34px repeat(24, 1fr); gap: 2px; font-size: 10px; color: var(--muted); }
.stats-heat div { aspect-ratio: 1; border-radius: 3px; min-width: 0; }
.stats-heat .label { aspect-ratio: auto; align-self: center; text-align: right; padding-right: 4px; }
.stats-heat .hour { aspect-ratio: auto; text-align: center; }
.stats-empty { color: var(--muted); padding: 24px 0; text-align: center; }
</style>
<section>
<div class="toolbar">
<select id="stats-range" aria-label="Time covered">
<option value="1">Last 24 hours</option>
<option value="7" selected>Last 7 days</option>
<option value="30">Last 30 days</option>
<option value="90">Last 90 days</option>
<option value="365">Last year</option>
</select>
<span class="hint" id="stats-note">Times are in your time zone.</span>
</div>
<div class="stats-tiles" id="stats-tiles"></div>
</section>
<div class="stats-grid">
<section>
<h2>Players online</h2>
<div class="stats-legend"><span>Average</span><span class="dim">Most at once</span></div>
<div id="stats-online"></div>
</section>
<section>
<h2>Logins</h2>
<div class="stats-legend"><span class="box">Logins</span><span class="box dim">Different players</span></div>
<div id="stats-logins"></div>
</section>
<section>
<h2>New accounts</h2>
<div id="stats-new"></div>
</section>
<section>
<h2>Busiest hours</h2>
<p class="hint">Average players online at each hour of the day.</p>
<div id="stats-hours"></div>
</section>
<section>
<h2>Week at a glance</h2>
<p class="hint">Average players online by day and hour: the lighter, the busier.</p>
<div id="stats-week"></div>
</section>
<section>
<h2>Most time played</h2>
<div class="table-wrap"><table>
<thead><tr><th>Player</th><th class="num">Playtime</th></tr></thead>
<tbody id="stats-top"></tbody>
</table></div>
<div class="stats-empty" id="stats-no-top" hidden>No playtime counted yet.</div>
</section>
</div>
<script>
(() => {
const SVG = "http://www.w3.org/2000/svg";
const W = 640;
const H = 220;
const PAD = {left: 40, right: 10, top: 10, bottom: 28};
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const byId = id => document.getElementById(id);
const svgEl = (tag, attrs = {}, text) => {
const node = document.createElementNS(SVG, tag);
for (const [name, value] of Object.entries(attrs)) {
node.setAttribute(name, value);
}
if (text !== undefined) {
node.textContent = text;
}
return node;
};
const htmlEl = (tag, text, className) => {
const node = document.createElement(tag);
if (text !== undefined) {
node.textContent = text;
}
if (className) {
node.className = className;
}
return node;
};
const played = seconds => {
const days = Math.floor(seconds / 86400);
const hours = Math.floor(seconds % 86400 / 3600);
const minutes = Math.floor(seconds % 3600 / 60);
if (days > 0) {
return `${days.toLocaleString()}d ${hours}h`;
}
if (hours > 0) {
return `${hours}h ${minutes}m`;
}
return `${minutes}m`;
};
const when = (seconds, withTime = true) => (seconds
? new Date(seconds * 1000).toLocaleString([], withTime ? {dateStyle: "medium", timeStyle: "short"} : {dateStyle: "medium"}) : "—");
// A round top for the y axis, and three steps up to it.
const scale = most => {
if (most <= 0) {
return {top: 1, ticks: [0, 1]};
}
const raw = most / 4;
const power = 10 ** Math.floor(Math.log10(raw));
const step = [1, 2, 2.5, 5, 10].map(f => f * power).find(f => f >= raw) || raw;
const nice = Math.max(1, step < 1 && Number.isInteger(most) ? 1 : step);
const top = Math.ceil(most / nice) * nice;
const ticks = [];
for (let tick = 0; tick <= top + 1e-9; tick += nice) {
ticks.push(Math.round(tick * 100) / 100);
}
return {top, ticks};
};
// the frame of a chart: the y axis's lines and numbers, and up to
// `labels` evenly spaced names along the bottom.
const frame = (top, ticks, names, every) => {
const svg = svgEl("svg", {viewBox: `0 0 ${W} ${H}`, class: "stats-chart", role: "img"});
const plotH = H - PAD.top - PAD.bottom;
for (const tick of ticks) {
const y = PAD.top + plotH - tick / top * plotH;
svg.append(svgEl("line", {x1: PAD.left, x2: W - PAD.right, y1: y, y2: y, class: "axis"}));
svg.append(svgEl("text", {x: PAD.left - 6, y: y + 4, "text-anchor": "end"}, tick.toLocaleString()));
}
const plotW = W - PAD.left - PAD.right;
names.forEach((name, index) => {
if (index % every === 0) {
svg.append(svgEl("text", {x: PAD.left + (index + 0.5) * plotW / names.length, y: H - 8, "text-anchor": "middle"}, name));
}
});
return svg;
};
const labelEvery = count => Math.max(1, Math.ceil(count / 8));
// bars, one or two to a slot: [{values, dim}], names under them, and
// what hovering a slot says.
const bars = (sets, names, tip) => {
const most = Math.max(0, ...sets.flatMap(set => set.values.filter(value => value !== null)));
const {top, ticks} = scale(most);
const svg = frame(top, ticks, names, labelEvery(names.length));
const plotW = W - PAD.left - PAD.right;
const plotH = H - PAD.top - PAD.bottom;
const slot = plotW / names.length;
const width = Math.max(1, slot * 0.8 / sets.length);
names.forEach((name, index) => {
const group = svgEl("g");
group.append(svgEl("title", {}, tip(index)));
group.append(svgEl("rect", {x: PAD.left + index * slot, y: PAD.top, width: slot, height: plotH, class: "hit"}));
sets.forEach((set, which) => {
const value = set.values[index] || 0;
const height = value / top * plotH;
group.append(svgEl("rect", {x: PAD.left + index * slot + slot * 0.1 + which * width, y: PAD.top + plotH - height, width, height,
class: set.dim ? "bar dim" : "bar"}));
});
svg.append(group);
});
return svg;
};
// lines through points (null leaves a gap): [{values, dim}].
const lines = (sets, names, tip) => {
const most = Math.max(0, ...sets.flatMap(set => set.values.filter(value => value !== null)));
const {top, ticks} = scale(most);
const svg = frame(top, ticks, names, labelEvery(names.length));
const plotW = W - PAD.left - PAD.right;
const plotH = H - PAD.top - PAD.bottom;
const x = index => PAD.left + (index + 0.5) * plotW / names.length;
const y = value => PAD.top + plotH - value / top * plotH;
for (const set of [...sets].reverse()) {
let d = "";
let drawing = false;
set.values.forEach((value, index) => {
if (value === null) {
drawing = false;
return;
}
d += `${drawing ? "L" : "M"}${x(index).toFixed(1)},${y(value).toFixed(1)}`;
drawing = true;
});
svg.append(svgEl("path", {d: d || "M0,0", class: set.dim ? "line dim" : "line"}));
}
const slot = plotW / names.length;
names.forEach((name, index) => {
const hit = svgEl("rect", {x: PAD.left + index * slot, y: PAD.top, width: slot, height: plotH, class: "hit"});
hit.append(svgEl("title", {}, tip(index)));
svg.append(hit);
});
return svg;
};
const render = data => {
const {summary} = data;
const hourly = data.bucketSeconds < 86400;
const tiles = [
[summary.online.toLocaleString(), "Online now"],
[summary.peak.count.toLocaleString(), "Most at once", summary.peak.at ? when(summary.peak.at) : ""],
[summary.peakEver.count.toLocaleString(), "Most ever", summary.peakEver.at ? when(summary.peakEver.at, false) : ""],
[summary.logins.toLocaleString(), "Logins"],
[summary.players.toLocaleString(), "Players", "who logged in"],
[summary.newAccounts.toLocaleString(), "New accounts", `${summary.firstLogins.toLocaleString()} played`],
[summary.averageSessionSeconds ? played(summary.averageSessionSeconds) : "—", "Average visit", `${summary.sessions.toLocaleString()} visits`],
[played(summary.playedSeconds), "Time played"],
[summary.accounts.toLocaleString(), "Accounts in all"],
];
byId("stats-tiles").replaceChildren(...tiles.map(([value, name, sub]) => {
const tile = htmlEl("div", undefined, "stats-tile");
tile.append(htmlEl("div", value, "value"), htmlEl("div", name, "name"));
if (sub) {
tile.append(htmlEl("div", sub, "sub"));
}
return tile;
}));
const series = data.series;
const bucketName = at => {
const date = new Date(at * 1000);
return hourly ? date.toLocaleTimeString([], {hour: "numeric"}) : date.toLocaleDateString([], {month: "short", day: "numeric"});
};
const bucketLong = at => {
const date = new Date(at * 1000);
return hourly ? date.toLocaleString([], {weekday: "short", hour: "numeric", minute: "2-digit"}) : date.toLocaleDateString([], {weekday: "short", dateStyle: "medium"});
};
const names = series.map(bucket => bucketName(bucket.at));
byId("stats-online").replaceChildren(lines(
[{values: series.map(bucket => bucket.average)}, {values: series.map(bucket => bucket.most), dim: true}], names,
index => `${bucketLong(series[index].at)}\naverage ${series[index].average ?? "—"} · most ${series[index].most ?? "—"}`));
byId("stats-logins").replaceChildren(bars(
[{values: series.map(bucket => bucket.logins)}, {values: series.map(bucket => bucket.players), dim: true}], names,
index => `${bucketLong(series[index].at)}\n${series[index].logins} logins · ${series[index].players} players`));
byId("stats-new").replaceChildren(bars(
[{values: series.map(bucket => bucket.newAccounts)}], names,
index => `${bucketLong(series[index].at)}\n${series[index].newAccounts} new`));
const hourName = hour => new Date(2000, 0, 1, hour).toLocaleTimeString([], {hour: "numeric"});
byId("stats-hours").replaceChildren(bars(
[{values: data.hours.map(hour => hour.average)}], data.hours.map((hour, index) => hourName(index)),
index => `${hourName(index)}\naverage ${data.hours[index].average ?? "—"} online · ${data.hours[index].logins} logins`));
const heat = htmlEl("div", undefined, "stats-heat");
const busiest = Math.max(0, ...data.week.flat().filter(value => value !== null));
heat.append(htmlEl("div", "", "label"));
for (let hour = 0; hour < 24; hour++) {
heat.append(htmlEl("div", hour % 6 === 0 ? String(hour) : "", "hour"));
}
// Monday first.
for (const day of [1, 2, 3, 4, 5, 6, 0]) {
heat.append(htmlEl("div", DAYS[day], "label"));
data.week[day].forEach((value, hour) => {
const cell = htmlEl("div");
const share = busiest > 0 && value !== null ? value / busiest : 0;
const level = value === null ? 20 : Math.round(26 + share * 229);
cell.style.background = `rgb(${level}, ${level}, ${level})`;
cell.title = `${DAYS[day]} ${hourName(hour)}: ${value === null ? "no data" : `average ${value}`}`;
heat.append(cell);
});
}
byId("stats-week").replaceChildren(heat);
byId("stats-top").replaceChildren(...data.topPlaytime.map(entry => {
const row = htmlEl("tr");
row.append(htmlEl("td", entry.username), htmlEl("td", played(entry.seconds), "num"));
return row;
}));
byId("stats-no-top").hidden = data.topPlaytime.length > 0;
};
let api = null;
let loadedAt = 0;
let loadedRange = null;
// `call` is the page's own: (path) -> {ok, data}. asked again at most
// once a minute, however often the page refreshes.
const load = async (call, force = false) => {
api = call;
const range = byId("stats-range").value;
if (!force && range === loadedRange && Date.now() - loadedAt < 60000) {
return;
}
const offset = -new Date().getTimezoneOffset();
const result = await call(`stats?days=${range}&offset=${offset}`);
if (result.ok) {
loadedAt = Date.now();
loadedRange = range;
render(result.data);
}
};
byId("stats-range").addEventListener("change", () => {
if (api) {
load(api, true);
}
});
window.statsView = {load};
})();
</script>
+3
View File
@@ -18,6 +18,7 @@ const reports = require("./lib/reports.js");
const roomInfo = require("./lib/roominfo.js");
const support = require("./lib/support.js");
const sfs = require("./lib/sfs.js");
const stats = require("./lib/stats.js");
const world = require("./lib/world.js");
// files this server makes are its own to read: accounts, logs, the cache.
@@ -43,6 +44,7 @@ const main = async () => {
modlog.load();
masterpieces.load();
retention.load();
stats.load(() => world.players().length);
panel.load();
await http.start();
await sfs.start(world);
@@ -51,6 +53,7 @@ const main = async () => {
// stopped on purpose: what is waiting to be written is written first.
const stop = code => {
stats.flush();
try {
accounts.flush();
}
+399 -6
View File
@@ -3,6 +3,9 @@ package
import avatar.AvatarManager;
import avatar.AvatarWorldView;
import com.sbi.debug.DebugUtility;
import com.sbi.graphics.PaletteHelper;
import den.DenXtCommManager;
import item.ItemXtCommManager;
import den.DenItem;
import item.Item;
import com.sbi.loader.ResourceStack;
@@ -30,6 +33,7 @@ package
import flash.external.ExternalInterface;
import flash.system.Capabilities;
import flash.system.Security;
import flash.system.System;
import flash.ui.Mouse;
import flash.utils.Dictionary;
import flash.utils.Timer;
@@ -86,6 +90,17 @@ package
private var _finderColourInput:TextField;
// the items drawn on the rows shown, by row number
private var _finderIcons:Object = {};
// a hex colour typed, as a local colour id for the previews only
// (PaletteHelper.customColors): the server makes the real one on Give
private var _finderHexKey:String = "";
private var _finderHexId:uint = 0;
private var _finderHexCount:uint = 0;
public function AJClient()
{
super();
@@ -291,7 +306,7 @@ package
}
catch(e:Error)
{
GlobalErrorCatch.reportToServer((param1 == 1 ? "chat filter: " : "item finder: ") + e + "\n" + e.getStackTrace());
GlobalErrorCatch.reportToServer((param1 == 1 ? "chat filter: " : "item giver: ") + e + "\n" + e.getStackTrace());
}
}
@@ -1202,10 +1217,14 @@ package
_filterOwnEntries = filterEntries(filterOwn);
}
// "xfa": the account has never chosen; the window is put to it once.
// "xfa": the account has never chosen; the rules are put to it first,
// then the window.
public static function onFilterAsk(param1:Object) : void
{
openTool(1);
openRules(function():void
{
openTool(1);
});
}
// is the word at `param2` of the plain words `param1` (and those after
@@ -1477,6 +1496,137 @@ package
drawChatFilter();
}
// the server's rules, word for word as the owner gave them
private static const RULES_HTML:String = "<font size=\"16\" color=\"#563421\"><b>[1] Be Respectful / Have Common Sense</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>This is quite self explanatory. Be kind, treat people how you would want to be treated. If someone is uncomfortable with something you are saying and or doing, please respect that of them and do not argue against it, even if it may seem ridiculous in your eyes.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[2] No Direct Harassment / Bullying</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>If you are being disrespectful towards another person, Moderators have every right to punish you. Please don't be an asshole. Thank you.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[3] Keep Personal Information for Yourself.</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>As friendly that people may seem on this platform, never share personal identifying details with ANYONE. This leads to a lot of unsafe situations. Please be safe and responsible with the information you give to other people.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[4] Keep Drama OUT</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>If you have personal issues with another person, it is not our responsibility unless said person is confirmed to be problematic towards something against the rules of our server. Please do not bring arguments into our public chat, you will be muted until things clear up. Keep it in DMS.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[5] No NSFW!</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>NSFW and Suggestive Content are entirely banned from the server, period. We do not want to be a place that allows predatory behavior to fester. If you are unsure of what specific details this goes under, feel free to ask in a ticket.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>[8] Report Any Issues</b></font><br><font size=\"13\" color=\"#6E4A2E\"><b>Issues can be anything from harassment, a person you are uncomfortable with, bugs, etc. Moderators are always happy to help!</b></font><br><br><font size=\"13\" color=\"#6E4A2E\"><b>Burrow gives players more freedom than the original game, including free chat. If you do not want to see certain content you may utilise the client side chat filter and block players, which has an option to completely hide them on your side.</b></font><br><br><font size=\"13\" color=\"#6E4A2E\"><b>These options are found in the in-game settings or player cards.</b></font><br><br><font size=\"16\" color=\"#563421\"><b>burrow.moe/terms</b></font>";
private var _rulesWin:Sprite;
private var _rulesText:TextField;
// what to do once the rules are closed (the chat filter, the first time)
private static var _rulesThen:Function;
// the rules, in the game's rules popup (its frame and text style), with
// room for all of them: the text scrolls with the wheel or the arrows.
// the game's own rules popup (GuiManager.displayRulesPopup) opens this.
private function buildRules() : void
{
var _loc1_:MovieClip = GETDEFINITIONBYNAME("ReportRulesPopupSkin");
var _loc2_:MovieClip = GETDEFINITIONBYNAME("ReportRulesPopupContent");
var _loc3_:int = 1;
var _loc4_:Sprite = new Sprite();
var _loc5_:MovieClip = null;
_rulesWin = new Sprite();
_rulesWin.graphics.beginFill(0,0.45);
_rulesWin.graphics.drawRect(0,0,900,550);
_rulesWin.graphics.endFill();
_loc4_.x = 450;
_loc4_.y = 275;
_rulesWin.addChild(_loc4_);
_loc4_.addChild(_loc1_);
_loc2_.x = _loc1_.c.x;
_loc2_.y = _loc1_.c.y;
_loc4_.addChild(_loc2_);
_loc1_.bx.addEventListener("mouseDown",onRulesCloseClick);
while(_loc3_ <= 5)
{
_loc2_["ruleTxt" + _loc3_].visible = false;
_loc2_["ruleBodyTxt" + _loc3_].visible = false;
_loc3_++;
}
_loc2_.titleTxt.text = "Burrow Rules";
_rulesText = _loc2_.ruleBodyTxt1;
_rulesText.visible = true;
_rulesText.multiline = true;
_rulesText.wordWrap = true;
_rulesText.mouseWheelEnabled = true;
_rulesText.selectable = false;
_rulesText.x = -245;
_rulesText.y = -158;
_rulesText.width = 462;
_rulesText.height = 338;
_rulesText.htmlText = RULES_HTML;
_loc5_ = GETDEFINITIONBYNAME("arrow_r_btnContOld");
_loc5_.rotation = -90;
_loc5_.x = 236;
_loc5_.y = -136;
_loc5_.name = "up";
_loc5_.addEventListener("mouseDown",onRulesArrow);
_loc2_.addChild(_loc5_);
_loc5_ = GETDEFINITIONBYNAME("arrow_r_btnContOld");
_loc5_.rotation = 90;
_loc5_.x = 236;
_loc5_.y = 160;
_loc5_.name = "down";
_loc5_.addEventListener("mouseDown",onRulesArrow);
_loc2_.addChild(_loc5_);
_rulesWin.addEventListener("mouseDown",onFinderMouse);
_rulesWin.addEventListener("mouseUp",onFinderMouse);
_rulesWin.addEventListener("click",onFinderMouse);
_rulesWin.addEventListener("mouseWheel",onFinderMouse);
_rulesWin.visible = false;
addChild(_rulesWin);
}
private function showRules(param1:Boolean) : void
{
if(_rulesWin == null)
{
buildRules();
}
_rulesWin.visible = param1;
if(param1)
{
_rulesText.scrollV = 1;
setChildIndex(_rulesWin,numChildren - 1);
}
}
private function onRulesArrow(param1:MouseEvent) : void
{
param1.stopPropagation();
_rulesText.scrollV += param1.currentTarget.name == "up" ? -4 : 4;
}
private function onRulesCloseClick(param1:MouseEvent) : void
{
var _loc2_:Function = _rulesThen;
param1.stopPropagation();
showRules(false);
_rulesThen = null;
if(_loc2_ != null)
{
_loc2_();
}
}
// the rules window, then `param1` once it is closed
public static function openRules(param1:Function = null) : void
{
if(_toolsInstance == null)
{
return;
}
try
{
_rulesThen = param1;
_toolsInstance.showRules(true);
}
catch(e:Error)
{
GlobalErrorCatch.reportToServer("rules: " + e + "\n" + e.getStackTrace());
}
}
public static function closeRules() : void
{
if(_toolsInstance != null && _toolsInstance._rulesWin != null)
{
_rulesThen = null;
_toolsInstance.showRules(false);
}
}
private function showChatFilter(param1:Boolean) : void
{
if(_filterWin == null)
@@ -1666,7 +1816,7 @@ package
_loc2_["ruleBodyTxt" + _loc3_].visible = false;
_loc3_++;
}
_loc2_.titleTxt.text = "Item Finder";
_loc2_.titleTxt.text = "Item Giver";
_finderStatus = _loc2_.ruleBodyTxt1;
_finderStatus.visible = true;
_finderStatus.wordWrap = false;
@@ -1683,6 +1833,7 @@ package
_finderPageLabel.width = 200;
_finderPageLabel.height = 24;
_finderPageLabel.text = "";
_loc2_.addChild(finderLink(_loc2_.ruleBodyTxt3,"Colour picker",FINDER_COLOUR_PICKER,60,154,150));
_finderInputBar = finderSearchBar(-247,-160,212,"Name or id",null,60,true);
_finderInput = _finderInputBar.searchTxt;
_loc2_.addChild(_finderInputBar);
@@ -1692,8 +1843,9 @@ package
finderButtonText(_finderKindButton,"All items");
_finderKindButton.addEventListener("mouseDown",onFinderKindClick);
_loc2_.addChild(_finderKindButton);
_finderColourBar = finderSearchBar(93,-160,156,"Colour ID","0-9",10,false);
_finderColourBar = finderSearchBar(93,-160,156,"Colour ID or #hex","0-9a-fA-F# ,",31,false);
_finderColourInput = _finderColourBar.searchTxt;
_finderColourInput.addEventListener("change",onFinderColourTyped);
_loc2_.addChild(_finderColourBar);
_finderRows = new Sprite();
_finderRows.x = 0;
@@ -1717,6 +1869,62 @@ package
addChild(_finder);
}
// made by players for working out custom colours
private static const FINDER_COLOUR_PICKER:String = "https://aj-color-picker.carrd.co/";
// `param1` (a text field of the artwork's, for its font) as a link at
// param4, param5, right-aligned in param6. the game's webview may open
// no window, so the page asks the client to open it in the system
// browser (ajOpenPage in public/game.html); clients before 1.1.2 drop
// that, so the address is copied as well.
private function finderLink(param1:TextField, param2:String, param3:String, param4:Number, param5:Number, param6:Number) : Sprite
{
var _loc7_:Sprite = new Sprite();
var _loc8_:TextFormat = param1.getTextFormat();
_loc8_.align = "right";
_loc8_.underline = true;
param1.parent.removeChild(param1);
param1.visible = true;
param1.wordWrap = false;
param1.selectable = false;
param1.x = 0;
param1.y = 0;
param1.width = param6;
param1.height = 24;
param1.defaultTextFormat = _loc8_;
param1.text = param2;
param1.setTextFormat(_loc8_);
_loc7_.addChild(param1);
_loc7_.x = param4;
_loc7_.y = param5;
_loc7_.buttonMode = true;
_loc7_.useHandCursor = true;
_loc7_.mouseChildren = false;
_loc7_.addEventListener("mouseDown",function(param1:MouseEvent):void
{
param1.stopPropagation();
try
{
System.setClipboard(param3);
}
catch(e:Error)
{
}
try
{
if(ExternalInterface.available)
{
ExternalInterface.call("ajOpenPage",param3);
}
}
catch(e:Error)
{
}
_finderStatus.text = "Link copied.";
});
return _loc7_;
}
private function showItemFinder(param1:Boolean) : void
{
if(_finder == null)
@@ -1753,6 +1961,16 @@ package
return;
}
var _loc2_:Boolean = _finder != null && _finder.visible;
// the rules: Esc closes them as their X does
if(_rulesWin != null && _rulesWin.visible)
{
if(param1.keyCode == 27)
{
onRulesCloseClick(new MouseEvent("mouseDown"));
}
param1.stopImmediatePropagation();
return;
}
// the chat filter's window: Esc leaves it as its X does, Enter
// saves, and no key gets past it to the game.
if(_filterWin != null && _filterWin.visible)
@@ -1870,6 +2088,17 @@ package
{
_finderRows.removeChildAt(0);
}
for each(var _loc6_:Object in _finderIcons)
{
try
{
_loc6_.destroy();
}
catch(e:Error)
{
}
}
_finderIcons = {};
var _loc5_:int = Math.max(1,Math.ceil(_finderResults.length / 6));
_loc2_ = _finderPage * 6;
while(_loc2_ < _finderResults.length && _loc2_ < _finderPage * 6 + 6)
@@ -1886,12 +2115,13 @@ package
_loc4_ = GETDEFINITIONBYNAME("buyBtnCont");
_loc4_.scaleX = 0.8;
_loc4_.scaleY = 0.8;
_loc4_.x = 160;
_loc4_.x = 152;
_loc4_.y = _loc3_.y;
_loc4_.name = "give" + _loc2_;
finderButtonText(_loc4_,"Give");
_loc4_.addEventListener("mouseDown",onFinderGiveClick);
_finderRows.addChild(_loc4_);
_finderRows.addChild(finderPreview(_loc1_,_loc2_,226,_loc3_.y));
_loc2_++;
}
_finderPageLabel.text = _finderResults.length == 0 ? "" : "Page " + (_finderPage + 1) + " of " + _loc5_;
@@ -1926,6 +2156,7 @@ package
{
_loc3_.colorIndex = (int(_loc3_.colorIndex) + 1) % int(_loc3_.colors);
_loc2_.currTxt.text = finderRowText(_loc3_);
recolourFinderPreview(int(_loc2_.name.substr(3)));
}
}
@@ -1945,6 +2176,11 @@ package
};
if(_finderColourInput.text.length > 0 && _loc2_.kind != "den")
{
if(_finderColourInput.text.indexOf("#") >= 0 ? finderHexColours(_finderColourInput.text) == null : !/^\s*[0-9]+\s*$/.test(_finderColourInput.text))
{
_finderStatus.text = "Colour: an id, or #RRGGBB";
return;
}
_loc5_.color = _finderColourInput.text;
}
_loc3_.data = JSON.stringify(_loc5_);
@@ -1956,6 +2192,163 @@ package
_loc4_.load(_loc3_);
}
// one to four "#RRGGBB" (spaces or commas between) as the four colour
// bands' RGB values, the last filling the rest; null if it is not that.
// the server reads the box the same way (lib/admin.js).
private static function finderHexColours(param1:String) : Array
{
var _loc2_:String = param1.replace(/^\s+|\s+$/g,"");
var _loc3_:Array = null;
var _loc4_:Array = [];
var _loc5_:int = 0;
if(!/^#[0-9a-f]{6}([\s,]+#[0-9a-f]{6}){0,3}$/i.test(_loc2_))
{
return null;
}
_loc3_ = _loc2_.split(/[\s,]+/);
while(_loc5_ < 4)
{
_loc4_.push(uint(parseInt(String(_loc3_[Math.min(_loc5_,_loc3_.length - 1)]).substr(1),16)));
_loc5_++;
}
return _loc4_;
}
// the colour a clothing row is drawn in: the box's colour id or hex
// colour, else the item's own colour that the row is on
private function finderPreviewColour(param1:Object) : uint
{
var _loc2_:String = _finderColourInput == null ? "" : _finderColourInput.text.replace(/^\s+|\s+$/g,"");
var _loc3_:Array = null;
var _loc4_:Object = null;
if(_loc2_.length > 0 && _loc2_.indexOf("#") >= 0)
{
_loc3_ = finderHexColours(_loc2_);
if(_loc3_ != null)
{
if(_loc3_.join(",") != _finderHexKey)
{
// a new id each time, so no drawing keeps the old palette;
// 0xFDFFFF00 and up is far past what the server hands out
_finderHexKey = _loc3_.join(",");
_finderHexId = uint(0xFDFFFF00 + (_finderHexCount++ & 0xFF));
PaletteHelper.customColors[_finderHexId] = _loc3_;
}
return _finderHexId;
}
}
else if(/^[0-9]+$/.test(_loc2_))
{
return uint(Number(_loc2_));
}
_loc4_ = ItemXtCommManager.getItemDef(int(param1.id));
if(_loc4_ == null || _loc4_.colors == null || _loc4_.colors.length == 0)
{
return 0;
}
return uint(_loc4_.colors[Math.min(int(param1.colorIndex),_loc4_.colors.length - 1)]);
}
// the row's item as the game draws it in a shop, in a box at the row's end
private function finderPreview(param1:Object, param2:int, param3:Number, param4:Number) : Sprite
{
var _loc5_:Sprite = new Sprite();
var _loc6_:Sprite = new Sprite();
var _loc7_:Matrix = new Matrix();
var _loc8_:* = null;
var _loc9_:Sprite = null;
_loc5_.x = param3;
_loc5_.y = param4;
_loc5_.mouseEnabled = false;
_loc5_.mouseChildren = false;
_loc5_.graphics.beginFill(7160624);
_loc5_.graphics.drawRoundRect(-19,-19,38,38,14,14);
_loc5_.graphics.endFill();
_loc5_.graphics.beginFill(10115109);
_loc5_.graphics.drawRoundRect(-18,-18,36,36,12,12);
_loc5_.graphics.endFill();
_loc7_.createGradientBox(32,32,Math.PI / 2,-16,-16);
_loc5_.graphics.beginGradientFill("linear",[11459790,15261660,16250099],[1,1,1],[0,127,255],_loc7_);
_loc5_.graphics.drawRoundRect(-16,-16,32,32,10,10);
_loc5_.graphics.endFill();
_loc5_.addChild(_loc6_);
try
{
if(param1.kind == "den")
{
if(DenXtCommManager.getDenItemDef(int(param1.id)) == null)
{
return _loc5_;
}
_loc8_ = new DenItem();
DenItem(_loc8_).initShopItem(int(param1.id),0);
}
else
{
if(ItemXtCommManager.getItemDef(int(param1.id)) == null)
{
return _loc5_;
}
_loc8_ = new Item();
Item(_loc8_).init(int(param1.id),0,finderPreviewColour(param1),null,true);
}
// fitted to the box once drawn, which may be before the icon is
// handed back when its picture was loaded already
_loc8_.imageLoadedCallback = function():void
{
var _loc1_:Number = 0;
if(_loc6_.numChildren > 0)
{
_loc6_.scaleX = _loc6_.scaleY = 1;
_loc1_ = Math.max(_loc6_.width,_loc6_.height);
if(_loc1_ > 0)
{
_loc6_.scaleX = _loc6_.scaleY = Math.min(1,30 / _loc1_);
}
}
};
_loc9_ = _loc8_.icon;
if(_loc9_ != null)
{
_loc6_.addChild(_loc9_);
if(_loc8_.isIconLoaded)
{
_loc8_.imageLoadedCallback();
}
}
_finderIcons[param2] = _loc8_;
}
catch(e:Error)
{
GlobalErrorCatch.reportToServer("item giver preview " + param1.kind + " " + param1.id + ": " + e);
}
return _loc5_;
}
private function recolourFinderPreview(param1:int) : void
{
var _loc2_:Item = _finderIcons[param1] as Item;
if(_loc2_ != null && _finderResults[param1] != null)
{
_loc2_.color = finderPreviewColour(_finderResults[param1]);
_loc2_.icon;
}
}
// the previews follow the colour box once what is in it reads as a
// colour, or is emptied
private function onFinderColourTyped(param1:Event) : void
{
var _loc2_:String = _finderColourInput.text.replace(/^\s+|\s+$/g,"");
if(_loc2_.length == 0 || /^[0-9]+$/.test(_loc2_) || finderHexColours(_loc2_) != null)
{
for(var _loc3_:String in _finderIcons)
{
recolourFinderPreview(int(_loc3_));
}
}
}
private function onFinderGiveDone(param1:Event) : void
{
_finderStatus.text = "Added to your inventory.";
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+32 -33
View File
@@ -365,8 +365,19 @@ package gui
var _loc1_:* = null;
DarkenManager.showLoadingSpiral(false);
KeepAlive.stopKATimer(avEditor);
removeListeners();
if(avEditor.tradeBtnUp && avEditor.tradeBtnUp.visible)
// the editor can be destroyed (leaving the room) before its artwork
// came, or after setting it up threw halfway (#1009, #2025 below)
if(avEditor)
{
try
{
removeListeners();
}
catch(e:Error)
{
}
}
if(avEditor && avEditor.tradeBtnUp && avEditor.tradeBtnUp.visible)
{
if(_itemTradeWindows)
{
@@ -394,7 +405,10 @@ package gui
}
if(_avatarEditorView)
{
avEditor.charBox.removeChild(_avatarEditorView);
if(_avatarEditorView.parent)
{
_avatarEditorView.parent.removeChild(_avatarEditorView);
}
_avatarEditorView.destroy();
_avatarEditorView = null;
_itemIdsOn = null;
@@ -480,8 +494,14 @@ package gui
}
_spirals = null;
AvatarManager.showAvtAndChatLayers(true);
DarkenManager.unDarken(avEditor);
_guiLayer.removeChild(avEditor);
if(avEditor)
{
DarkenManager.unDarken(avEditor);
if(avEditor.parent)
{
avEditor.parent.removeChild(avEditor);
}
}
}
public function get onCloseCallback() : Function
@@ -1222,7 +1242,10 @@ package gui
avEditor.colorsTabUp.visible = false;
avEditor.eyesTabUp.visible = false;
avEditor.patternTabUp.visible = true;
avEditor.colorTableBlock.patternsAndEyes.specialAvtIconCont.visible = _worldAvatar.customAvId != -1;
// special animals get the pattern colour table too, in place of
// their icon: any colour, as for the others. the arrows still
// step through their preset colours.
avEditor.colorTableBlock.patternsAndEyes.specialAvtIconCont.visible = false;
if(avEditor.colorTableBlock.patternsAndEyes.contains(_colorTableEyes))
{
avEditor.colorTableBlock.patternsAndEyes.removeChild(_colorTableEyes);
@@ -1232,27 +1255,7 @@ package gui
{
avEditor.colorTableBlock.patternsAndEyes.removeChild(_colorTableEyes);
}
if(_worldAvatar.customAvId != -1)
{
if(_customAvtIcon)
{
avEditor.colorTableBlock.patternsAndEyes.specialAvtIconCont.addChild(_customAvtIcon);
}
else
{
_loc2_ = gMainFrame.userInfo.getAvatarDefByAvType(_worldAvatar.customAvId,true) as CustomAvatarDef;
if(_loc2_)
{
_loadingSpiral = new LoadingSpiral(avEditor.colorTableBlock.patternsAndEyes.specialAvtIconCont,avEditor.colorTableBlock.patternsAndEyes.width * 0.5,avEditor.colorTableBlock.patternsAndEyes.height * 0.5);
_loadingMediaHelper = new MediaHelper();
_loadingMediaHelper.init(_loc2_.iconRefId,onCustomIconLoaded);
}
}
}
else
{
avEditor.colorTableBlock.patternsAndEyes.addChild(_colorTablePatterns);
}
avEditor.colorTableBlock.patternsAndEyes.addChild(_colorTablePatterns);
if(_patterns.length > 0)
{
if(_patterns.length <= 1 && _worldAvatar.customAvId == -1)
@@ -1352,12 +1355,8 @@ package gui
{
if(_loc2_)
{
if(_loc2_.patternRefIds.length > 1)
{
avEditor.colorsTabUp.activateGrayState(true);
avEditor.colorsTabDnBtn.activateGrayState(true);
openTab(2);
}
// the colours tab stays open to special animals with several
// patterns (it was greyed out, the pattern tab opened instead).
_loc5_ = _loc2_.patternRefIds.indexOf(_loc1_.getAccItem(_loc4_).defId);
if(_loc5_ != -1)
{
+15 -3
View File
@@ -666,6 +666,8 @@ package buddy
{
var _loc2_:Function = null;
var _loc1_:int = 0;
// first, so that nothing below that throws can leave it set
AvatarManager.buddyCardAvatarView = null;
if(_closeCallback != null)
{
_loc2_ = _closeCallback;
@@ -751,7 +753,11 @@ package buddy
{
_banCard = null;
}
_popupLayer.removeChild(_buddyCardMC);
// a card destroyed twice, or before it was shown (#2007)
if(_buddyCardMC && _buddyCardMC.parent)
{
_buddyCardMC.parent.removeChild(_buddyCardMC);
}
_buddyCardMC = null;
AvatarManager.buddyCardAvatarView = null;
if(_playerAvatars)
@@ -1829,6 +1835,10 @@ package buddy
}
_mainAvatarView.destroy();
_mainAvatarView = null;
// left pointing at the destroyed view, its userName is null and
// AvatarManager.avatarCreateResponse throws for every player
// who comes into the room after (before their clothes go on).
AvatarManager.buddyCardAvatarView = null;
}
}
@@ -2398,7 +2408,8 @@ package buddy
_loc3_ = 0;
while(_loc3_ < _views.length)
{
if(_views[_loc3_] == param1.mediaHelper)
// the card closed before the game icons came (#1009)
if(_views[_loc3_] == param1.mediaHelper && _pvpItemWindows != null && _loc3_ < _pvpItemWindows.bg.numChildren)
{
_loc2_ = MovieClip(_pvpItemWindows.bg.getChildAt(_loc3_));
param1 = param1.getChildAt(0) as MovieClip;
@@ -3235,7 +3246,8 @@ package buddy
public function get currBuddyCardUserName() : String
{
if(_currUserName != "")
// null until a card was first filled in (#1009)
if(_currUserName)
{
return _currUserName.toLowerCase();
}
+619
View File
@@ -0,0 +1,619 @@
package buddy
{
import com.sbi.popup.SBPopup;
import flash.display.DisplayObjectContainer;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.utils.Dictionary;
import flash.utils.Timer;
import gui.GuiManager;
import gui.LoadingSpiral;
import gui.PlayerSearch;
import gui.WindowAndScrollbarGenerator;
import gui.itemWindows.ItemWindowBuddyList;
import localization.LocalizationManager;
import room.RoomManagerWorld;
public class BuddyList
{
private static const BUDDY_LIST_X_OFFSET:int = 5;
private static const BUDDY_LIST_Y_OFFSET:int = 40;
private static var _playerSearch:PlayerSearch;
private static var _buddyListPopup:SBPopup;
private static var _buddyListContent:MovieClip;
private static var _buddyListBtn:MovieClip;
private static var _buddyListWorldPopup:MovieClip;
private static var _requestingForWorldBuddyList:Boolean;
private static var _worldSelectCallback:Function;
private static var _currentSelectedUsername:String;
private static var _currentSelectedItem:Object;
private static var _currentSelectedIndex:int;
private static var _itemWindowBuddyList:WindowAndScrollbarGenerator;
private static var _itemWindowBuddyListWorld:WindowAndScrollbarGenerator;
private static var _buddyListReferFriendBg:MovieClip;
private static var _buddyListReferAFriendBtn:MovieClip;
private static var _buddyListHowDidYouHearBtn:MovieClip;
private static var _glowTimer:Timer;
private static var _howDidYouHearPopup:HowDidYouHear;
private static var _referAFriendPopup:ReferAFriend;
private static var _popupLayer:DisplayLayer;
private static var _loadingSpiral:LoadingSpiral;
private static var _worldPopupLoadingSpiral:LoadingSpiral;
private static var _hasRequestedReferralAssociation:Boolean;
public static var listRequested:Boolean;
public function BuddyList()
{
super();
}
public static function init(param1:DisplayLayer, param2:MovieClip, param3:Boolean = false) : void
{
_popupLayer = param1;
_buddyListBtn = param2;
if(!Utility.canBuddy())
{
_buddyListBtn.activateGrayState(true);
}
_buddyListContent = GETDEFINITIONBYNAME("BuddyListContent");
LocalizationManager.translateId(_buddyListContent.buddyListTitleTxt,11250);
_buddyListContent.counterTxt.text = String(BuddyManager.buddyCount) + "/" + String(BuddyManager.getMaxBuddyCount());
_buddyListPopup = new SBPopup(_popupLayer,GETDEFINITIONBYNAME("BuddyListPopup"),_buddyListContent,false,true,false,false);
_buddyListPopup.closeCallback = buddyListClosedCallback;
_buddyListPopup.x = _buddyListPopup.width * 0.5 + 5;
_buddyListPopup.y = _buddyListPopup.skin.s.ba.height * 0.5 + 40;
_buddyListReferFriendBg = _buddyListPopup.skin.s.ba.referFriendBg;
_buddyListReferAFriendBtn = _buddyListPopup.skin.s.ba.referAFriend;
_buddyListHowDidYouHearBtn = _buddyListPopup.skin.s.ba.howDidYouHear;
_loadingSpiral = new LoadingSpiral(DisplayObjectContainer(_buddyListPopup.content),-15);
_hasRequestedReferralAssociation = false;
_glowTimer = new Timer(5000);
addListeners();
if(param3)
{
onBuddyListChange(null);
}
}
public static function rebuildBtn(param1:MovieClip) : void
{
if(_buddyListBtn)
{
_buddyListBtn.removeEventListener("mouseDown",buddyListBtnHandler);
}
_buddyListBtn = param1;
if(Utility.canBuddy())
{
_buddyListBtn.addEventListener("mouseDown",buddyListBtnHandler,false,0,true);
}
else
{
_buddyListBtn.activateGrayState(true);
}
_buddyListBtn.glow.visible = false;
LocalizationManager.translateId(_buddyListContent.buddyListTitleTxt,11250);
}
public static function destroy() : void
{
var _loc1_:int = 0;
removeListeners();
_buddyListContent = null;
if(_itemWindowBuddyList)
{
_itemWindowBuddyList.destroy();
_itemWindowBuddyList = null;
}
if(_buddyListPopup)
{
_buddyListPopup.destroy();
_buddyListPopup = null;
}
}
public static function get visible() : Boolean
{
return _buddyListPopup.visible;
}
public static function closeBuddyList() : void
{
if(_buddyListPopup && _buddyListPopup.visible)
{
_buddyListPopup.close();
removePopupListeners();
GuiManager.toolTip.resetTimerAndSetVisibility();
_buddyListBtn.downToUpState();
}
onPlayerSearchClose();
}
public static function updateBuddyTimeLeftHosting() : void
{
if(_itemWindowBuddyList)
{
_itemWindowBuddyList.callUpdateInWindow();
}
}
private static function onHasReferralAssociationResponse(param1:int) : void
{
_hasRequestedReferralAssociation = true;
_buddyListReferFriendBg.visible = true;
if(param1 == 1)
{
_buddyListReferAFriendBtn.visible = true;
_buddyListHowDidYouHearBtn.visible = false;
}
else
{
_buddyListReferAFriendBtn.visible = false;
_buddyListHowDidYouHearBtn.visible = true;
}
if(_buddyListPopup.visible)
{
addReferAFriendListeners();
}
}
private static function onBuddyListChange(param1:Event) : void
{
if(_buddyListWorldPopup)
{
buildInWorldBuddyList(null,_currentSelectedItem,null,_currentSelectedUsername);
}
_loadingSpiral.visible = false;
_buddyListContent.counterTxt.text = String(BuddyManager.buddyCount) + "/" + String(BuddyManager.getMaxBuddyCount());
var _loc2_:Number = -1;
if(_itemWindowBuddyList)
{
_loc2_ = _itemWindowBuddyList.scrollYValue;
// not always still in the block when the list changes (#2025)
if(_itemWindowBuddyList.parent)
{
_itemWindowBuddyList.parent.removeChild(_itemWindowBuddyList);
}
_itemWindowBuddyList.destroy();
}
_itemWindowBuddyList = new WindowAndScrollbarGenerator();
_itemWindowBuddyList.init((_buddyListPopup.content as MovieClip).itemBlock.width,(_buddyListPopup.content as MovieClip).itemBlock.height,-5,_loc2_,1,10,BuddyManager.buddyCount,0,2,0,9,ItemWindowBuddyList,buildBuddyList(),"",0,{
"mouseDown":buddyListClickOnBuddyHandler,
"mouseOver":buddyListOverBuddyHandler,
"mouseOut":buddyListOutBuddyHandler
},null,null,true,false,false,false,false);
(_buddyListPopup.content as MovieClip).itemBlock.addChild(_itemWindowBuddyList);
}
public static function buildBuddyList() : Array
{
var _loc4_:Array = [];
var _loc2_:Dictionary = BuddyManager.buddyList;
var _loc3_:int = BuddyManager.buddyCount;
_buddyListContent.counterTxt.text = String(BuddyManager.buddyCount) + "/" + String(BuddyManager.getMaxBuddyCount());
if(_loc2_ && _loc3_ > 0)
{
for each(var _loc1_:Buddy in _loc2_)
{
_loc4_.push({
"userName":_loc1_.userName,
"moderatedUserName":_loc1_.userNameModerated,
"moderatedUserNameFlag":_loc1_.userNameModeratedFlag,
"onlineStatus":_loc1_.onlineStatus,
"accountType":_loc1_.accountType,
"uuid":_loc1_.uuid,
"timeLeftHostingCustomParty":_loc1_.timeLeftHostingCustomParty
});
}
_loc4_.sortOn(["onlineStatus","userName"],[2,1]);
}
return _loc4_;
}
public static function buildInWorldBuddyList(param1:MovieClip, param2:Object, param3:Function, param4:String) : void
{
var _loc8_:Array = null;
var _loc6_:Dictionary = null;
var _loc7_:int = 0;
if(!param1 || param1 && !closeWorldBuddyList() || !listRequested)
{
if(param1)
{
_worldSelectCallback = param3;
if(_buddyListWorldPopup == null)
{
_buddyListWorldPopup = GETDEFINITIONBYNAME("portalLinkBuddyListPopup");
}
if(_worldPopupLoadingSpiral == null)
{
_worldPopupLoadingSpiral = new LoadingSpiral(_buddyListWorldPopup,_buddyListWorldPopup.width * 0.5,_buddyListWorldPopup.height * 0.5);
}
RoomManagerWorld.instance.layerManager.room_chat.addChild(_buddyListWorldPopup);
_buddyListWorldPopup.x = param1.x - _buddyListWorldPopup.width * 0.5;
_buddyListWorldPopup.y = param1.y + 15;
}
if(!listRequested)
{
_worldPopupLoadingSpiral.visible = true;
BuddyXtCommManager.sendBuddyListRequest();
listRequested = true;
_requestingForWorldBuddyList = true;
_currentSelectedUsername = param4;
_currentSelectedItem = param2;
}
else
{
if(!param1 || !_itemWindowBuddyListWorld || _currentSelectedItem != param2)
{
_loc8_ = [];
_loc6_ = BuddyManager.buddyList;
_loc7_ = BuddyManager.buddyCount;
if(_loc6_ && _loc7_ > 0)
{
for each(var _loc5_:Buddy in _loc6_)
{
_loc8_.push({
"userName":_loc5_.userName,
"moderatedUserName":_loc5_.userNameModerated,
"moderatedUserNameFlag":_loc5_.userNameModeratedFlag,
"uuid":_loc5_.uuid
});
}
_loc8_.sortOn(["userName"],[2,1]);
}
_currentSelectedUsername = param4;
_currentSelectedItem = param2;
_currentSelectedIndex = -1;
if(_itemWindowBuddyListWorld)
{
_itemWindowBuddyListWorld.destroy();
_itemWindowBuddyListWorld = null;
}
while(_buddyListWorldPopup.numChildren > 2)
{
_buddyListWorldPopup.removeChildAt(_buddyListWorldPopup.numChildren - 1);
}
_itemWindowBuddyListWorld = new WindowAndScrollbarGenerator();
_itemWindowBuddyListWorld.init(_buddyListWorldPopup.itemBlock.width,_buddyListWorldPopup.itemBlock.height,0,0,1,5,0,0,2,0,1,ItemWindowBuddyList,_loc8_,"",0,{"mouseDown":worldBuddyListClickOnBuddyHandler},{
"isSelection":true,
"currSelectedUsername":param4
},null,true,false,false,false,false);
_buddyListWorldPopup.itemBlock.addChild(_itemWindowBuddyListWorld);
}
_worldPopupLoadingSpiral.visible = false;
}
}
}
public static function updateWorldBuddyListPosition(param1:MovieClip) : void
{
if(_buddyListWorldPopup && _buddyListWorldPopup.parent)
{
_buddyListWorldPopup.x = param1.x - _buddyListWorldPopup.width * 0.5;
_buddyListWorldPopup.y = param1.y + 15;
}
}
public static function closeWorldBuddyList() : Boolean
{
if(_buddyListWorldPopup && _buddyListWorldPopup.parent)
{
_buddyListWorldPopup.parent.removeChild(_buddyListWorldPopup);
_worldSelectCallback = null;
return true;
}
return false;
}
public static function isOverWorldBuddyList(param1:int, param2:int) : Boolean
{
var _loc3_:Point = null;
if(_buddyListWorldPopup && _buddyListWorldPopup.parent)
{
_loc3_ = RoomManagerWorld.instance.convertWorldToScreen(param1,param2);
return _buddyListWorldPopup.hitTestPoint(_loc3_.x,_loc3_.y,false);
}
return false;
}
public static function destroyInWorldBuddyList() : void
{
closeWorldBuddyList();
_buddyListWorldPopup = null;
if(_itemWindowBuddyListWorld)
{
_itemWindowBuddyListWorld.destroy();
_itemWindowBuddyListWorld = null;
}
_worldSelectCallback = null;
_currentSelectedUsername = "";
_currentSelectedItem = null;
}
public static function requestBuddyListIfNeeded(param1:Function) : void
{
if(!listRequested)
{
BuddyXtCommManager.sendBuddyListRequest(param1);
listRequested = true;
}
else if(param1 != null)
{
param1();
}
}
public static function updateSelectedInWorldBuddyIndex(param1:int) : void
{
_currentSelectedIndex = param1;
}
private static function worldBuddyListClickOnBuddyHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
if(_worldSelectCallback != null)
{
if(_currentSelectedUsername != "" && _currentSelectedUsername.toLowerCase() == param1.currentTarget.buddyPortalUsername())
{
param1.currentTarget.turnOffBuddySelection();
_currentSelectedIndex = -1;
_currentSelectedUsername = "";
}
else
{
if(_currentSelectedIndex != -1)
{
MovieClip(_itemWindowBuddyListWorld.bg.getChildAt(_currentSelectedIndex)).turnOffBuddySelection();
}
param1.currentTarget.setBuddySelection();
_currentSelectedIndex = param1.currentTarget.index;
_currentSelectedUsername = param1.currentTarget.getBuddy().userName;
}
_worldSelectCallback(_currentSelectedUsername);
}
}
private static function buddyListClickOnBuddyHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
var _loc2_:Buddy = param1.currentTarget.getBuddy();
if(_loc2_.userName.indexOf("Liza") < 0)
{
BuddyManager.showBuddyCard({
"userName":_loc2_.userName,
"onlineStatus":_loc2_.onlineStatus
});
}
GuiManager.toolTip.resetTimerAndSetVisibility();
AJAudio.playSubMenuBtnClick();
}
private static function buddyListOverBuddyHandler(param1:MouseEvent) : void
{
(param1.currentTarget as ItemWindowBuddyList).showRecycleBtn(true);
}
private static function buddyListOutBuddyHandler(param1:MouseEvent) : void
{
(param1.currentTarget as ItemWindowBuddyList).showRecycleBtn(false);
}
private static function buddyListBtnHandler(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!param1.currentTarget.isGray)
{
if(!listRequested)
{
BuddyXtCommManager.sendBuddyListRequest();
listRequested = true;
}
GuiManager.onExitRoom(true);
if(_buddyListPopup.visible)
{
_buddyListPopup.close();
removePopupListeners();
}
else
{
if(Utility.daysSinceCreated() > 3)
{
_buddyListReferAFriendBtn.visible = true;
_buddyListHowDidYouHearBtn.visible = false;
addReferAFriendListeners();
}
else if(!_hasRequestedReferralAssociation)
{
_buddyListReferFriendBg.visible = false;
_buddyListReferAFriendBtn.visible = false;
_buddyListHowDidYouHearBtn.visible = false;
ReferAFriendXtCommManager.sendHasReferralAssociate(onHasReferralAssociationResponse);
}
else
{
addReferAFriendListeners();
}
glowTimerHandler(null);
_buddyListPopup.open();
addPopupListeners();
}
}
}
private static function buddyListClosedCallback() : void
{
_buddyListBtn.downToUpState();
}
public static function startBuddyListBtnGlow() : void
{
if(_buddyListBtn)
{
_buddyListBtn.glow.visible = true;
}
AJAudio.playBuddyOnlineOfflineSound();
if(_glowTimer.running)
{
_glowTimer.stop();
}
_glowTimer.start();
}
private static function glowTimerHandler(param1:TimerEvent) : void
{
_glowTimer.stop();
if(_buddyListBtn)
{
_buddyListBtn.glow.visible = false;
}
}
private static function onSearchBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
_playerSearch = new PlayerSearch();
_playerSearch.init(onPlayerSearchClose);
GuiManager.toolTip.resetTimerAndSetVisibility();
}
private static function onSearchBtnOver(param1:MouseEvent) : void
{
param1.stopPropagation();
GuiManager.toolTip.init(GuiManager.guiLayer,LocalizationManager.translateIdOnly(14638),180,305);
GuiManager.toolTip.startTimer(param1);
}
private static function onSearchBtnOut(param1:MouseEvent) : void
{
param1.stopPropagation();
GuiManager.toolTip.resetTimerAndSetVisibility();
}
private static function onPlayerSearchClose() : void
{
if(_playerSearch)
{
_playerSearch.destroy();
_playerSearch = null;
}
}
private static function onReferAFriendBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
_referAFriendPopup = new ReferAFriend(onReferAFriendClose);
}
private static function onReferAFriendClose() : void
{
_referAFriendPopup.destroy();
_referAFriendPopup = null;
}
private static function onHowDidYouHearBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
_howDidYouHearPopup = new HowDidYouHear(onHowDidYouHearClose);
}
private static function onHowDidYouHearClose(param1:Boolean) : void
{
_howDidYouHearPopup.destroy();
_howDidYouHearPopup = null;
if(param1)
{
_buddyListHowDidYouHearBtn.visible = false;
_buddyListHowDidYouHearBtn.removeEventListener("mouseDown",onHowDidYouHearBtn);
_buddyListReferAFriendBtn.visible = true;
_buddyListReferAFriendBtn.addEventListener("mouseDown",onReferAFriendBtn,false,0,true);
}
}
private static function addPopupListeners() : void
{
_buddyListContent.searchBtn.addEventListener("mouseDown",onSearchBtn,false,0,true);
_buddyListContent.searchBtn.addEventListener("mouseOver",onSearchBtnOver,false,0,true);
_buddyListContent.searchBtn.addEventListener("mouseOut",onSearchBtnOut,false,0,true);
}
private static function addReferAFriendListeners() : void
{
if(_buddyListReferAFriendBtn.visible)
{
_buddyListReferAFriendBtn.addEventListener("mouseDown",onReferAFriendBtn,false,0,true);
}
else if(_buddyListHowDidYouHearBtn.visible)
{
_buddyListHowDidYouHearBtn.addEventListener("mouseDown",onHowDidYouHearBtn,false,0,true);
}
}
private static function removePopupListeners() : void
{
if(_buddyListContent)
{
_buddyListContent.searchBtn.removeEventListener("mouseDown",onSearchBtn);
_buddyListContent.searchBtn.removeEventListener("mouseOver",onSearchBtnOver);
_buddyListContent.searchBtn.removeEventListener("mouseOut",onSearchBtnOut);
if(_buddyListReferAFriendBtn.visible)
{
_buddyListReferAFriendBtn.removeEventListener("mouseDown",onReferAFriendBtn);
}
else if(_buddyListHowDidYouHearBtn.visible)
{
_buddyListHowDidYouHearBtn.removeEventListener("mouseDown",onHowDidYouHearBtn);
}
}
}
private static function addListeners() : void
{
_glowTimer.addEventListener("timer",glowTimerHandler,false,0,true);
BuddyManager.eventDispatcher.addEventListener("OnBuddyList",onBuddyListChange,false,0,true);
BuddyManager.eventDispatcher.addEventListener("OnBuddyChanged",onBuddyListChange,false,0,true);
if(Utility.canBuddy())
{
_buddyListBtn.addEventListener("mouseDown",buddyListBtnHandler,false,0,true);
}
}
private static function removeListeners() : void
{
if(Utility.canBuddy())
{
_buddyListBtn.removeEventListener("mouseDown",buddyListBtnHandler);
}
_glowTimer.removeEventListener("timer",glowTimerHandler);
BuddyManager.eventDispatcher.removeEventListener("OnBuddyList",onBuddyListChange);
BuddyManager.eventDispatcher.removeEventListener("OnBuddyChanged",onBuddyListChange);
}
}
}
@@ -0,0 +1,61 @@
method
name "onTutorialGLReceived"
flag HAS_PARAM_NAMES
param QName(PackageNamespace(""),"int")
param QName(PackageNamespace("collection"),"StreamDefCollection")
paramname "glId"
paramname "streamDefs"
returns QName(PackageNamespace(""),"void")
body
maxstack 4
localcount 3
initscopedepth 0
maxscopedepth 1
code
getlocal0
pushscope
getlocal2
iffalse ofs_empty
getlocal2
getproperty QName(PackageNamespace(""),"length")
pushbyte 0
ifgt ofs_go
ofs_empty:
returnvoid
ofs_go:
getlocal2
pushbyte 0
callproperty QName(PackageNamespace(""),"getStreamDefItem"), 1
findproperty QName(PrivateNamespace("gui:BulletinBoard"),"_currTutorialStreamDef")
swap
setproperty QName(PrivateNamespace("gui:BulletinBoard"),"_currTutorialStreamDef")
pushshort 178
findproperty QName(PrivateNamespace("gui:BulletinBoard"),"_introCloseId")
swap
setproperty QName(PrivateNamespace("gui:BulletinBoard"),"_introCloseId")
getlex QName(PackageNamespace("localization"),"LocalizationManager")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_bulletinBoardPopup")
getproperty Multiname("videoTitleTxt",[PrivateNamespace("gui:BulletinBoard"),ProtectedNamespace("gui:BulletinBoard"),StaticProtectedNs("gui:BulletinBoard"),StaticProtectedNs("Object"),PackageNamespace("gui"),PackageInternalNs("gui"),PrivateNamespace("FilePrivateNS:BulletinBoard"),PackageNamespace(""),Namespace("http://adobe.com/AS3/2006/builtin")])
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_currTutorialStreamDef")
getproperty QName(PackageNamespace(""),"baseTitleId")
callpropvoid QName(PackageNamespace(""),"translateId"), 2
findpropstrict QName(PackageNamespace("loader"),"MediaHelper")
constructprop QName(PackageNamespace("loader"),"MediaHelper"), 0
findproperty QName(PrivateNamespace("gui:BulletinBoard"),"_loadingMediaHelper")
swap
setproperty QName(PrivateNamespace("gui:BulletinBoard"),"_loadingMediaHelper")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_loadingMediaHelper")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_currTutorialStreamDef")
getproperty QName(PackageNamespace(""),"thumbnailId")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"onMediaItemLoaded")
pushtrue
callpropvoid QName(PackageNamespace(""),"init"), 3
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_mediaHelpers")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_loadingMediaHelper")
callpropvoid QName(Namespace("http://adobe.com/AS3/2006/builtin"),"push"), 1
returnvoid
end ; code
end ; body
end ; method
@@ -0,0 +1,51 @@
method
name "onWhatsNewVideosLoaded"
flag HAS_PARAM_NAMES
param QName(PackageNamespace(""),"int")
param QName(PackageNamespace("collection"),"StreamDefCollection")
paramname "glId"
paramname "streamDefs"
returns QName(PackageNamespace(""),"void")
body
maxstack 4
localcount 3
initscopedepth 0
maxscopedepth 1
code
getlocal0
pushscope
getlocal2
iffalse ofs_empty
getlocal2
getproperty QName(PackageNamespace(""),"length")
pushbyte 0
ifgt ofs_go
ofs_empty:
returnvoid
ofs_go:
getlocal2
pushbyte 0
callproperty QName(PackageNamespace(""),"getStreamDefItem"), 1
findproperty QName(PrivateNamespace("gui:BulletinBoard"),"_currWhatsNewStreamDef")
swap
setproperty QName(PrivateNamespace("gui:BulletinBoard"),"_currWhatsNewStreamDef")
findpropstrict QName(PackageNamespace("loader"),"MediaHelper")
constructprop QName(PackageNamespace("loader"),"MediaHelper"), 0
findproperty QName(PrivateNamespace("gui:BulletinBoard"),"_loadingMediaHelper")
swap
setproperty QName(PrivateNamespace("gui:BulletinBoard"),"_loadingMediaHelper")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_loadingMediaHelper")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_currWhatsNewStreamDef")
getproperty QName(PackageNamespace(""),"thumbnailId")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"onMediaItemLoaded")
pushtrue
callpropvoid QName(PackageNamespace(""),"init"), 3
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_mediaHelpers")
getlex QName(PrivateNamespace("gui:BulletinBoard"),"_loadingMediaHelper")
callpropvoid QName(Namespace("http://adobe.com/AS3/2006/builtin"),"push"), 1
returnvoid
end ; code
end ; body
end ; method
+204
View File
@@ -0,0 +1,204 @@
package shop
{
import collection.IitemCollection;
import currency.UserCurrency;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import gui.DarkenManager;
import gui.GuiManager;
import gui.UpsellManager;
import item.ItemXtCommManager;
import loader.MediaHelper;
import localization.LocalizationManager;
public class BundleShop
{
private var _mediaHelper:MediaHelper;
private var _bundleShop:MovieClip;
private const SHOP_ID:int = 1;
private const MEDIA_ID:int = 8266;
private var _unfilteredItemArray:IitemCollection;
private var _unfilteredColorsArray:Array;
private var _shopItemArray:IitemCollection;
private var _itemColorsArray:Array;
private var _currShopItemArray:IitemCollection;
private var _diamondCost:int;
private var _closeCallback:Function;
public function BundleShop(param1:Function)
{
super();
DarkenManager.showLoadingSpiral(true);
_closeCallback = param1;
_mediaHelper = new MediaHelper();
_mediaHelper.init(8266,onShopLoaded);
}
private function onShopLoaded(param1:MovieClip) : void
{
_bundleShop = param1.getChildAt(0) as MovieClip;
_mediaHelper = new MediaHelper();
_mediaHelper.init(8267,onImageLoaded);
ItemXtCommManager.requestShopList(gotItemListCallback,1);
}
private function onImageLoaded(param1:MovieClip) : void
{
_bundleShop.itemLayer.addChild(param1.getChildAt(0));
}
private function gotItemListCallback(param1:IitemCollection, param2:String, param3:Boolean, param4:int, param5:Array = null) : void
{
if(param3)
{
_diamondCost = param4;
_unfilteredItemArray = param1;
_unfilteredColorsArray = param5;
LocalizationManager.translateId(_bundleShop.bodyTxt,35572);
if(param2 != "")
{
LocalizationManager.translateId(_bundleShop.titleTxt,int(param2));
}
setupTags();
filterItemLists();
}
}
private function filterItemLists() : void
{
_shopItemArray = new IitemCollection(_unfilteredItemArray.concatCollection(null));
if(_unfilteredColorsArray)
{
_itemColorsArray = _unfilteredColorsArray.concat();
}
else
{
_itemColorsArray = null;
}
GenericListXtCommManager.filterIitems(_shopItemArray,true,_itemColorsArray);
DarkenManager.showLoadingSpiral(false);
if(_shopItemArray.length == 0)
{
destroy();
return;
}
_bundleShop.visible = true;
_bundleShop.x = 900 * 0.5;
_bundleShop.y = 550 * 0.5;
GuiManager.guiLayer.addChild(_bundleShop);
DarkenManager.darken(_bundleShop);
addListeners();
}
private function setupTags() : void
{
if(UserCurrency.hasEnoughCurrency(3,_diamondCost))
{
if(_bundleShop.tag.currentFrameLabel != "diamondgreen")
{
_bundleShop.tag.gotoAndPlay("diamondgreen");
}
_bundleShop.tag.txt.textColor = "0x386630";
}
else
{
if(_bundleShop.tag.currentFrameLabel != "diamondred")
{
_bundleShop.tag.gotoAndPlay("diamondred");
}
_bundleShop.tag.txt.textColor = "0x800000";
}
_bundleShop.tag.txt.text = Utility.convertNumberToString(_diamondCost);
_bundleShop.tag.visible = true;
}
private function addListeners() : void
{
_bundleShop.addEventListener("mouseDown",onPopupDown,false,0,true);
_bundleShop.bx.addEventListener("mouseDown",onCloseBtn,false,0,true);
_bundleShop.buyBtn.addEventListener("mouseDown",onBuyBtn,false,0,true);
}
private function removeListeners() : void
{
_bundleShop.removeEventListener("mouseDown",onPopupDown);
_bundleShop.bx.removeEventListener("mouseDown",onCloseBtn);
_bundleShop.buyBtn.removeEventListener("mouseDown",onBuyBtn);
}
private function onPopupDown(param1:MouseEvent) : void
{
param1.stopPropagation();
}
private function onCloseBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
destroy();
}
private function onBuyBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!gMainFrame.userInfo.isMember)
{
UpsellManager.displayPopup("diamondShop","buyBundle/");
return;
}
if(!UserCurrency.hasEnoughCurrency(3,_diamondCost))
{
UpsellManager.displayPopup("","extraDiamonds");
return;
}
ItemXtCommManager.requestBuyDiamondBundle(1,onDiamondPurchaseComplete);
}
private function onDiamondPurchaseComplete(param1:Object) : void
{
destroy();
if(param1[2] == "true")
{
UserCurrency.setCurrency(param1[3],3);
GuiManager.setupInGameRedemptions();
}
}
private function destroy() : void
{
if(_bundleShop)
{
removeListeners();
}
if(_mediaHelper)
{
_mediaHelper.destroy();
_mediaHelper = null;
}
// an empty shelf (this server keeps the bundle podium empty) closes
// the shop before it was ever shown
if(_bundleShop && _bundleShop.parent)
{
DarkenManager.unDarken(_bundleShop);
_bundleShop.parent.removeChild(_bundleShop);
}
_bundleShop = null;
if(_closeCallback != null)
{
_closeCallback(false);
_closeCallback = null;
}
}
}
}
+3 -1
View File
@@ -479,7 +479,9 @@ package gui
}
else
{
chatMsgText.maxChars = 70;
// 150 here, where the original stopped at 70. the server takes
// up to config.maxChatLength.
chatMsgText.maxChars = 150;
}
}
+702
View File
@@ -0,0 +1,702 @@
package gui
{
import avatar.Avatar;
import com.sbi.client.KeepAlive;
import com.sbi.popup.SBYesNoPopup;
import den.DenRoomItem;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import gui.itemWindows.ItemWindowAnimal;
import loader.MediaHelper;
import localization.LocalizationManager;
import shop.Shop;
import shop.ShopManager;
public class DenSwitcher
{
private const MIN_NUM_DENS:int = 1;
private const DENSWITCH_MEDIA_ID:int = 1168;
private var _numTotalSlots:int;
private var _playerAvatar:Avatar;
private var _guiLayer:DisplayLayer;
private var _closeCallback:Function;
private var _shop:Shop;
private var _views:Array;
private var _activeIdx:int;
private var _idx:int;
private var _recycling:Boolean;
private var _recyclingOnly:Boolean;
private var _loadingMediaHelper:MediaHelper;
private var _mediaHelpers:Array;
private var _contentItems:Array;
private var _switchContent:MovieClip;
private var _closeBtn:MovieClip;
private var _choosingContent:MovieClip;
private var _scrollButtons:SBScrollbar;
private var _itemWindows:WindowGenerator;
private var _openStoreOnly:Boolean;
private var _firstOpenIdx:int;
private var _glId:int;
private var _storeItemIndex:int;
public function DenSwitcher()
{
super();
}
public function init(param1:Avatar, param2:DisplayLayer, param3:Boolean = false, param4:Boolean = false, param5:Function = null, param6:int = -1, param7:int = -1, param8:int = -1, param9:int = 450, param10:int = 250) : void
{
DarkenManager.showLoadingSpiral(true);
_playerAvatar = param1;
_guiLayer = param2;
_closeCallback = param5;
_recyclingOnly = param3;
_openStoreOnly = param4;
_firstOpenIdx = param6;
_storeItemIndex = param8;
_numTotalSlots = 200;
_mediaHelpers = [];
if(param7 == -1)
{
_glId = 13;
}
else
{
_glId = param7;
}
_loadingMediaHelper = new MediaHelper();
_loadingMediaHelper.init(1168,onMediaItemLoaded,true);
_mediaHelpers.push(_loadingMediaHelper);
}
public function destroy() : void
{
var _loc1_:int = 0;
removeListeners();
KeepAlive.stopKATimer(_switchContent);
_loc1_ = 0;
while(_loc1_ < _views.length)
{
if(_views[_loc1_])
{
_views[_loc1_].destroy();
_views[_loc1_] = null;
}
_loc1_++;
}
if(_shop)
{
_shop.destroy();
_shop = null;
}
if(_switchContent)
{
if(_switchContent.root.parent == _guiLayer)
{
_guiLayer.removeChild(_switchContent.root);
}
DarkenManager.unDarken(MovieClip(_switchContent.root));
_switchContent.root.removeEventListener("mouseDown",onPopup);
_switchContent = null;
if(_closeBtn)
{
_closeBtn = null;
}
if(_contentItems)
{
_contentItems = null;
}
}
if(_itemWindows)
{
_itemWindows.destroy();
_itemWindows = null;
}
_recyclingOnly = false;
_recycling = false;
_closeCallback = null;
}
public function close() : void
{
if(_closeCallback != null)
{
_closeCallback();
}
else
{
destroy();
}
}
public function get idx() : int
{
return _idx;
}
public function showDenSwitcher(param1:Boolean, param2:int = -1) : void
{
if(_switchContent && _switchContent.root.visible != param1)
{
_switchContent.root.visible = param1;
if(param1)
{
DarkenManager.darken(MovieClip(_switchContent.root));
}
else if(param2 == -1)
{
DarkenManager.unDarken(MovieClip(_switchContent.root));
}
if(param2 != -1)
{
_switchContent.root.parent.setChildIndex(_switchContent.root,param2);
_switchContent.root.visible = param1;
}
}
else if(param1)
{
_switchContent.root.parent.setChildIndex(_switchContent.root,_switchContent.root.parent.numChildren - 1);
}
}
public function rebuildWindows(param1:Boolean, param2:Function) : void
{
_closeCallback = param2;
_recyclingOnly = param1;
buildWindows();
}
public function get currCloseCallback() : Function
{
return _closeCallback;
}
private function onMediaItemLoaded(param1:MovieClip) : void
{
var _loc2_:Boolean = false;
if(param1)
{
_closeBtn = MovieClip(param1.getChildAt(0)).bx;
_switchContent = MovieClip(param1.getChildAt(0)).c;
KeepAlive.startKATimer(_switchContent);
_guiLayer.addChild(param1);
param1.addEventListener("mouseDown",onPopup,false,0,true);
param1.x = 900 * 0.5;
param1.y = 550 * 0.5;
DarkenManager.showLoadingSpiral(false);
DarkenManager.darken(param1);
addListeners();
_loc2_ = _firstOpenIdx != -1;
initVisibilityAndStates();
buildWindows();
if(_openStoreOnly)
{
param1.visible = false;
onItemWindowDown(null);
}
else if(_loc2_)
{
onItemWindowDown(null);
}
}
}
private function onPopup(param1:MouseEvent) : void
{
param1.stopPropagation();
}
private function initVisibilityAndStates() : void
{
_activeIdx = DenSwitch.activeDenIdx;
_switchContent.buyPopup.tag.visible = false;
_switchContent.oopsPopup.body_txt.text = "";
LocalizationManager.translateId(_switchContent.switchTitleTxt,11271);
_switchContent.buyPopup.tag.txt.text = "";
_switchContent.buyPopup.paw.gray.visible = false;
_switchContent.buyPopup.banner.visible = false;
_switchContent.buyPopup.lock.visible = false;
_switchContent.buyPopup.lockOpen.visible = false;
_switchContent.buyPopup.colorChange_btn.visible = false;
_switchContent.buyPopup.paw.visible = true;
_switchContent.buyPopup.visible = false;
_switchContent.oopsPopup.visible = false;
_switchContent.oopsCostPopup.visible = false;
_switchContent.denShopTag.visible = false;
_switchContent.saveAmlTag.visible = false;
_switchContent.newAmlTag.visible = false;
}
private function buildWindows() : void
{
var _loc5_:int = 0;
var _loc2_:MovieClip = null;
var _loc1_:MediaHelper = null;
if(_scrollButtons)
{
_scrollButtons.destroy();
_scrollButtons = null;
}
if(_itemWindows)
{
_itemWindows.destroy();
_itemWindows = null;
}
var _loc6_:int = _numTotalSlots;
var _loc7_:int = Math.min(_loc6_,4);
var _loc3_:int = Math.ceil(_loc7_ / 2);
_itemWindows = new WindowGenerator();
_itemWindows.init(_loc7_,_loc3_,_loc6_,1,2,0,ItemWindowAnimal,DenSwitch.denList.getCoreArray(),"icon",{
"mouseDown":onItemWindowDown,
"mouseOver":onItemWindowOver,
"mouseOut":onItemWindowOut
},{"recylingOnly":_recyclingOnly},null,false,false);
_switchContent.itemBlock.addChild(_itemWindows);
_views = new Array(_numTotalSlots);
_contentItems = new Array(_numTotalSlots);
_activeIdx = DenSwitch.activeDenIdx;
_loc5_ = 0;
while(_loc5_ < _numTotalSlots)
{
_loc2_ = MovieClip(_itemWindows.bg.getChildAt(_loc5_));
_contentItems[_loc5_] = _loc2_;
if(DenSwitch.denList.getDenRoomItem(_loc5_) != null)
{
_loc1_ = new MediaHelper();
_loc1_.init(DenSwitch.denList.getDenRoomItem(_loc5_).mediaId,mediaHelperCallback,DenSwitch.denList.getDenRoomItem(_loc5_).isMemberOnly);
_views[_loc5_] = _loc1_;
}
else if(_firstOpenIdx == -1)
{
_firstOpenIdx = _loc5_;
}
_loc5_++;
}
if(_firstOpenIdx == -1)
{
_firstOpenIdx = 0;
}
var _loc4_:int = DenSwitch.numDens;
if(_loc4_ > 1)
{
_switchContent.recycleBtn.gray.visible = false;
_switchContent.recycleBtn.mouse.visible = true;
_switchContent.recycleBtn.down.visible = false;
}
else
{
_switchContent.recycleBtn.gray.visible = true;
_switchContent.recycleBtn.mouse.visible = false;
_switchContent.recycleBtn.down.visible = false;
}
if(_recyclingOnly)
{
_recycling = true;
}
if(_loc4_ >= _numTotalSlots && !_recyclingOnly)
{
_switchContent.denShopTag.visible = true;
}
else
{
_switchContent.denShopTag.visible = false;
}
_scrollButtons = new SBScrollbar();
_scrollButtons.init(_itemWindows,840,440,-6,"scrollbar2",221.95);
_switchContent.itemCounter.counterTxt.text = DenSwitch.numDens + "/" + 200;
}
public function switchDenCallback(param1:Boolean) : void
{
if(param1)
{
close();
}
else
{
DarkenManager.darken(_switchContent.oopsPopup);
LocalizationManager.translateId(_switchContent.oopsPopup.body_txt,11272);
_switchContent.oopsPopup.visible = true;
}
DarkenManager.showLoadingSpiral(false);
}
private function recycleDenCallback(param1:Boolean, param2:int) : void
{
var _loc3_:MovieClip = null;
var _loc5_:int = 0;
var _loc4_:int = 0;
if(param1)
{
if(_recyclingOnly)
{
DarkenManager.showLoadingSpiral(false);
if(_closeCallback != null)
{
_closeCallback(true);
}
else
{
destroy();
}
}
else
{
_loc3_ = _contentItems[param2];
if(_views[param2])
{
_views[param2].destroy();
_views[param2] = null;
}
_recycling = false;
_loc5_ = 0;
while(_loc5_ < _numTotalSlots)
{
_contentItems[_loc5_].recycle.visible = false;
_loc5_++;
}
_loc3_.resetWindow(param2);
_loc4_ = DenSwitch.numDens;
if(_loc4_ <= 1)
{
_switchContent.recycleBtn.gray.visible = true;
_switchContent.recycleBtn.mouse.visible = false;
_switchContent.recycleBtn.down.visible = false;
}
if(_loc4_ >= _numTotalSlots)
{
_switchContent.denShopTag.visible = true;
}
else
{
_switchContent.denShopTag.visible = false;
}
_switchContent.itemCounter.counterTxt.text = _loc4_ + "/" + 200;
}
}
else
{
DarkenManager.darken(_switchContent.oopsPopup);
LocalizationManager.translateId(_switchContent.oopsPopup.body_txt,11273);
_switchContent.oopsPopup.visible = true;
_recycling = true;
}
DarkenManager.showLoadingSpiral(false);
}
private function purchasedDenRoomCallback() : void
{
if(_shop)
{
_shop.onDenPurchase();
}
if(!_openStoreOnly)
{
closeDenShop(true);
}
// bought from a land's den shop the switcher is only ever hidden, and
// closing the shop may have closed it (#1009 below); and a den whose
// def this client lacks has no item. the den is bought either way.
if(_switchContent == null || _itemWindows == null || _contentItems == null || _contentItems[_idx] == null
|| DenSwitch.denList == null || DenSwitch.denList.getDenRoomItem(_idx) == null)
{
return;
}
var _loc2_:DenRoomItem = DenSwitch.denList.getDenRoomItem(_idx);
ItemWindowAnimal(MovieClip(_itemWindows).bg.getChildAt(_idx)).currItem = _loc2_;
var _loc3_:MovieClip = _contentItems[_idx];
_loc3_.buyDen.visible = false;
_loc3_.denWindow.visible = true;
LocalizationManager.updateToFit(_loc3_.denWindow.txt,_loc2_.name,false,false,false);
_loc3_.denWindow.sel.visible = false;
var _loc1_:MediaHelper = new MediaHelper();
_loc1_.init(_loc2_.mediaId,mediaHelperCallback,_loc2_.isMemberOnly);
_views[_idx] = _loc1_;
var _loc4_:int = DenSwitch.numDens;
if(_loc4_ >= _numTotalSlots)
{
_switchContent.denShopTag.visible = true;
}
else
{
_switchContent.denShopTag.visible = false;
}
if(_loc4_ > 1)
{
_switchContent.recycleBtn.gray.visible = false;
_switchContent.recycleBtn.mouse.visible = true;
_switchContent.recycleBtn.down.visible = false;
}
if(_shop)
{
_shop.denItemIdx = _firstOpenIdx = Math.max(0,DenSwitch.nextFreeSlotIdx);
}
_switchContent.itemCounter.counterTxt.text = _loc4_ + "/" + 200;
}
public function closeDenShop(param1:Boolean = false) : void
{
if(_shop)
{
_shop.destroy();
_shop = null;
}
if(_openStoreOnly)
{
close();
}
}
private function mediaHelperCallback(param1:MovieClip) : void
{
var _loc2_:int = 0;
_loc2_ = 0;
while(_loc2_ < _views.length)
{
if(_views[_loc2_] == param1.mediaHelper)
{
if(param1.passback && !gMainFrame.userInfo.isMember)
{
_contentItems[_loc2_].gray.amlMask.amlBox.addChild(param1);
}
else
{
(_contentItems[_loc2_].denWindow as MovieClip).itemBlock.addChild(param1);
}
break;
}
_loc2_++;
}
}
private function confirmRecycleHandler(param1:Object) : void
{
if(param1.status)
{
DenSwitch.removeDen(_idx,recycleDenCallback);
DarkenManager.showLoadingSpiral(true);
}
}
private function onItemWindowDown(param1:MouseEvent) : void
{
if(param1)
{
param1.stopPropagation();
_idx = param1.currentTarget.index;
}
else
{
_idx = _firstOpenIdx;
}
if(_contentItems[_idx].buyDen.visible || _openStoreOnly)
{
if(!ShopManager.isWorldShopOpen())
{
_shop = new Shop();
_shop.init(_glId,1060,_playerAvatar,_guiLayer,closeDenShop,_idx,purchasedDenRoomCallback,_openStoreOnly,_storeItemIndex);
}
}
else if(_contentItems[_idx].gray.visible == true && !_recycling)
{
if(!gMainFrame.userInfo.isMember)
{
UpsellManager.displayPopup("dens","useLockedDen/" + DenSwitch.denList.getDenRoomItem(_idx).name);
}
}
else if(_recycling)
{
if(_idx == _activeIdx)
{
DarkenManager.darken(_switchContent.oopsPopup);
LocalizationManager.translateId(_switchContent.oopsPopup.body_txt,11274);
_switchContent.oopsPopup.visible = true;
}
else if(_idx == 0)
{
DarkenManager.darken(_switchContent.oopsPopup);
LocalizationManager.translateId(_switchContent.oopsPopup.body_txt,11275);
_switchContent.oopsPopup.visible = true;
}
else
{
new SBYesNoPopup(_guiLayer,LocalizationManager.translateIdAndInsertOnly(14715,Utility.convertNumberToString(DenSwitch.denList.getDenRoomItem(idx).recycleValue)),true,confirmRecycleHandler);
}
}
else if((_contentItems[_idx].denWindow as MovieClip).visible == true)
{
if(_idx != _activeIdx)
{
DarkenManager.showLoadingSpiral(true);
DenSwitch.switchDens(_idx,switchDenCallback);
}
}
}
private function onItemWindowOver(param1:MouseEvent) : void
{
param1.stopPropagation();
_idx = param1.currentTarget.index;
if((_contentItems[_idx].denWindow as MovieClip).currentFrameLabel != "mouse")
{
(_contentItems[_idx].denWindow as MovieClip).gotoAndPlay("mouse");
}
AJAudio.playSubMenuBtnRollover();
}
private function onItemWindowOut(param1:MouseEvent) : void
{
param1.stopPropagation();
_idx = param1.currentTarget.index;
if((_contentItems[_idx].denWindow as MovieClip).currentFrameLabel != "out")
{
(_contentItems[_idx].denWindow as MovieClip).gotoAndPlay("out");
}
}
private function onOopsClose(param1:MouseEvent) : void
{
param1.stopPropagation();
DarkenManager.unDarken(_switchContent.oopsPopup);
_switchContent.oopsPopup.visible = false;
}
private function onClose(param1:MouseEvent) : void
{
param1.stopPropagation();
close();
}
private function onRecycleDown(param1:MouseEvent) : void
{
var _loc2_:int = 0;
var _loc3_:int = 0;
param1.stopPropagation();
if(!_recyclingOnly)
{
if(_recycling)
{
_loc2_ = 0;
while(_loc2_ < _numTotalSlots)
{
_contentItems[_loc2_].recycle.visible = false;
_loc2_++;
}
_recycling = false;
}
else if(!_switchContent.recycleBtn.gray.visible)
{
_recycling = true;
_loc3_ = 0;
while(_loc3_ < _numTotalSlots)
{
if(_views[_loc3_])
{
if(!_contentItems[_loc3_].buyDen.visible)
{
_contentItems[_loc3_].recycle.visible = true;
}
}
_loc3_++;
}
}
else
{
_switchContent.recycleBtn.mouse.visible = false;
}
}
}
private function onRecycleOver(param1:MouseEvent) : void
{
param1.stopPropagation();
GuiManager.toolTip.init(_guiLayer,LocalizationManager.translateIdOnly(14626),25,490);
GuiManager.toolTip.startTimer(param1);
}
private function onRecycleOut(param1:MouseEvent) : void
{
param1.stopPropagation();
GuiManager.toolTip.resetTimerAndSetVisibility();
}
private function onMoreDenDown(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!_recyclingOnly)
{
_shop = new Shop();
_shop.init(_glId,1040,_playerAvatar,_guiLayer,closeDenShop,-1,purchasedDenRoomCallback);
}
}
private function addListeners() : void
{
if(_closeBtn)
{
_closeBtn.addEventListener("mouseDown",onClose,false,0,true);
}
if(_switchContent)
{
_switchContent.recycleBtn.addEventListener("mouseDown",onRecycleDown,false,0,true);
_switchContent.recycleBtn.addEventListener("mouseOver",onRecycleOver,false,0,true);
_switchContent.recycleBtn.addEventListener("mouseOut",onRecycleOut,false,0,true);
_switchContent.oopsPopup.closeBtn.addEventListener("mouseDown",onOopsClose,false,0,true);
_switchContent.denShopTag.denShopBtn.addEventListener("mouseDown",onMoreDenDown,false,0,true);
}
}
private function removeListeners() : void
{
var _loc1_:int = 0;
_loc1_ = 0;
while(_loc1_ < _numTotalSlots)
{
if(_contentItems[_loc1_])
{
_contentItems[_loc1_].removeEventListener("mouseDown",onItemWindowDown);
_contentItems[_loc1_].removeEventListener("rollOver",onItemWindowOver);
_contentItems[_loc1_].removeEventListener("rollOut",onItemWindowOut);
}
_loc1_++;
}
if(_closeBtn)
{
_closeBtn.removeEventListener("mouseDown",onClose);
}
if(_switchContent)
{
_switchContent.recycleBtn.removeEventListener("mouseDown",onRecycleDown);
_switchContent.recycleBtn.removeEventListener("mouseOver",onRecycleOver);
_switchContent.recycleBtn.removeEventListener("mouseOut",onRecycleOut);
_switchContent.oopsPopup.closeBtn.removeEventListener("mouseDown",onOopsClose);
_switchContent.denShopTag.denShopBtn.removeEventListener("mouseDown",onMoreDenDown);
}
}
}
}
+999
View File
@@ -0,0 +1,999 @@
package game.distanceChallenge
{
import achievement.AchievementManager;
import achievement.AchievementXtCommManager;
import com.sbi.corelib.audio.SBAudio;
import com.sbi.corelib.audio.SBMusic;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.utils.getDefinitionByName;
import flash.utils.getTimer;
import game.GameBase;
import game.IMinigame;
import game.MinigameManager;
import game.SoundManager;
import localization.LocalizationManager;
public class DistanceChallenge extends GameBase implements IMinigame
{
private static const POPUP_X:int = 450;
private static const POPUP_Y:int = 275;
public static const BACKGROUND_TYPES_TOTAL:int = 6;
public static const BACKGROUND_TYPES_SANDTRAP:int = 1;
public static const BACKGROUND_TYPES_HARDICE:int = 2;
public static const BACKGROUND_TYPES_SNOWDRIFT:int = 3;
public static const BACKGROUND_TYPES_GEYSER:int = 4;
public static const BACKGROUND_TYPES_ASH:int = 5;
public static const BACKGROUND_TYPES_VOLCANO:int = 6;
public var _soundMan:SoundManager;
private var _facts:Array = [{
"image":"9b1",
"text":LocalizationManager.translateIdOnly(11394)
},{
"image":"9b3",
"text":LocalizationManager.translateIdOnly(11395)
},{
"image":"7b1",
"text":LocalizationManager.translateIdOnly(11396)
},{
"image":"6b1",
"text":LocalizationManager.translateIdOnly(11397)
},{
"image":"9b6",
"text":LocalizationManager.translateIdOnly(11398)
},{
"image":"9b3_2",
"text":LocalizationManager.translateIdOnly(11399)
},{
"image":"3b1",
"text":LocalizationManager.translateIdOnly(11400)
},{
"image":"3b1_2",
"text":LocalizationManager.translateIdOnly(11401)
},{
"image":"9b1_2",
"text":LocalizationManager.translateIdOnly(11402)
},{
"image":"9b4",
"text":LocalizationManager.translateIdOnly(11403)
},{
"image":"9b4_2",
"text":LocalizationManager.translateIdOnly(11404)
},{
"image":"9b5",
"text":LocalizationManager.translateIdOnly(11405)
},{
"image":"9b3_3",
"text":LocalizationManager.translateIdOnly(11406)
}];
public var myId:uint;
public var _pIDs:Array;
public var _dbIDs:Array;
private var _sceneLoaded:Boolean;
private var _bInit:Boolean;
public var _layerBackgroundSky:Sprite;
public var _layerBackgroundMiddle:Sprite;
public var _layerBackgroundGround:Sprite;
public var _layerBackgroundObstacle:Sprite;
public var _layerBackgroundLauncher:Sprite;
public var _layerPlayer:Sprite;
public var _layerSkyMove:Number;
public var _layerGroundMove:Number;
public var _particles:Array;
public var _sky:Array;
public var _backgroundElements:Array;
public var _activeBackgroundType:int;
public var _addBackgroundGroundX:int;
public var _lastChangeBackgroundGroundX:int;
public var _addMiddleX:int;
public var _lastChangeMiddleX:int;
public var _obstacleOffset:int;
public var _windSound:SoundChannel;
public var _gearsSound:SoundChannel;
public var _nextBackgroundSwitch:int;
private var _lastTime:int;
private var _frameTime:Number;
private var _gameTime:Number;
public var _displayAchievementTimer:Number;
public var _score:Object;
public var _launcher:Object;
public var _transition:Object;
public var _gameOverTimer:Number;
public var _recordDistance:Number;
public var _gemsEarned:int;
public var _lastRot:Number;
public var _player:DistanceChallengePlayer;
public var SFX_ARM_GEARS:Class;
public var SFX_ARM_WIND:Class;
private const _sounds:Array = ["armadillo_bounce.mp3","armadillo_spray.mp3","armadillo_launch.mp3","armadillo_prairie_dog.mp3","aj_armadillo_outro.mp3","armdadillo_collision1.mp3","armdadillo_collision2.mp3","armdadillo_collision3.mp3","armadillo_intro.mp3","armadillo_stinger_success.mp3","armadillo_passby1.mp3","armadillo_passby2.mp3","armadillo_superman_close.mp3","armadillo_superman_open.mp3","armadillo_wonder_woman.mp3","armadillo_cactus_collision.mp3","armadillo_steam.mp3","armadillo_collision_snowman.mp3","armadillo_swing.mp3","aj_ls_steam.mp3","aj_ls_stump_imp.mp3","armadillo_bounce.mp3","armadillo_bounce.mp3","armadillo_bounce.mp3","armadillo_bounce.mp3","armadillo_bounce.mp3","armadillo_bounce.mp3","armadillo_bounce.mp3"];
internal var _soundNameArmBounce:String = _sounds[0];
internal var _soundNameArmGeyser:String = _sounds[1];
internal var _soundNameArmLaunch:String = _sounds[2];
internal var _soundNameArmMole:String = _sounds[3];
internal var _soundNameArmOutro:String = _sounds[4];
internal var _soundNameArmCollision1:String = _sounds[5];
internal var _soundNameArmCollision2:String = _sounds[6];
internal var _soundNameArmCollision3:String = _sounds[7];
internal var _soundNameArmIntro:String = _sounds[8];
internal var _soundNameArmSuccess:String = _sounds[9];
internal var _soundNameArmPassBy1:String = _sounds[10];
internal var _soundNameArmPassBy2:String = _sounds[11];
internal var _soundNameArmSpmnClose:String = _sounds[12];
internal var _soundNameArmSpmnOpen:String = _sounds[13];
internal var _soundNameArmWonderwmn:String = _sounds[14];
internal var _soundNameArmCactusClsn:String = _sounds[15];
internal var _soundNameArmSteam:String = _sounds[16];
internal var _soundNameArmSnwmnClsn:String = _sounds[17];
internal var _soundNameArmSwing:String = _sounds[18];
internal var _soundNameArmLsSteam:String = _sounds[19];
internal var _soundNameArmStump:String = _sounds[20];
public var _SFX_Music:SBMusic;
public var _musicLoop:SoundChannel;
public function DistanceChallenge()
{
super();
init();
}
private function loadSounds() : void
{
_soundMan.addSoundByName(_audioByName[_soundNameArmBounce],_soundNameArmBounce,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmGeyser],_soundNameArmGeyser,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmLaunch],_soundNameArmLaunch,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmMole],_soundNameArmMole,0.55);
_soundMan.addSoundByName(_audioByName[_soundNameArmOutro],_soundNameArmOutro,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmCollision1],_soundNameArmCollision1,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmCollision2],_soundNameArmCollision2,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmCollision3],_soundNameArmCollision3,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmIntro],_soundNameArmIntro,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmSuccess],_soundNameArmSuccess,0.62);
_soundMan.addSoundByName(_audioByName[_soundNameArmPassBy1],_soundNameArmPassBy1,0.5);
_soundMan.addSoundByName(_audioByName[_soundNameArmPassBy2],_soundNameArmPassBy2,0.5);
_soundMan.addSoundByName(_audioByName[_soundNameArmSpmnClose],_soundNameArmSpmnClose,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmSpmnOpen],_soundNameArmSpmnOpen,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmWonderwmn],_soundNameArmWonderwmn,1.24);
_soundMan.addSoundByName(_audioByName[_soundNameArmCactusClsn],_soundNameArmCactusClsn,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmSteam],_soundNameArmSteam,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmSnwmnClsn],_soundNameArmSnwmnClsn,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmSwing],_soundNameArmSwing,0.58);
_soundMan.addSoundByName(_audioByName[_soundNameArmLsSteam],_soundNameArmLsSteam,1);
_soundMan.addSoundByName(_audioByName[_soundNameArmStump],_soundNameArmStump,1);
_soundMan.addSound(SFX_ARM_WIND,0.2,"SFX_ARM_WIND");
_soundMan.addSound(SFX_ARM_GEARS,0.2,"SFX_ARM_GEARS");
}
public function start(param1:uint, param2:Array) : void
{
myId = param1;
_pIDs = param2;
init();
}
public function end(param1:Array) : void
{
if(_gameTime > 15 && MinigameManager.minigameInfoCache && MinigameManager.minigameInfoCache.currMinigameId != -1)
{
AchievementXtCommManager.requestSetUserVar(MinigameManager.minigameInfoCache.getMinigameInfo(MinigameManager.minigameInfoCache.currMinigameId).gameCountUserVarRef,1);
}
releaseBase();
if(_musicLoop)
{
_musicLoop.stop();
_musicLoop = null;
}
stage.removeEventListener("keyDown",replayKeyDown);
stage.removeEventListener("keyDown",greatJobKeyDown);
stage.removeEventListener("enterFrame",heartbeat);
stage.removeEventListener("keyDown",fireKeyDown);
stage.removeEventListener("mouseDown",mouseClickHandler);
resetGame();
_bInit = false;
removeLayer(_layerBackgroundSky);
removeLayer(_layerBackgroundMiddle);
removeLayer(_layerBackgroundGround);
removeLayer(_layerBackgroundObstacle);
removeLayer(_layerBackgroundLauncher);
removeLayer(_layerPlayer);
removeLayer(_guiLayer);
_layerBackgroundSky = null;
_layerBackgroundMiddle = null;
_layerBackgroundGround = null;
_layerBackgroundObstacle = null;
_layerBackgroundLauncher = null;
_layerPlayer = null;
_guiLayer = null;
MinigameManager.leave();
}
private function init() : void
{
_displayAchievementTimer = 0;
if(!_bInit)
{
_particles = [];
_layerBackgroundSky = new Sprite();
_layerBackgroundMiddle = new Sprite();
_layerBackgroundGround = new Sprite();
_layerBackgroundObstacle = new Sprite();
_layerBackgroundLauncher = new Sprite();
_layerPlayer = new Sprite();
_layerBackgroundSky.mouseEnabled = false;
_layerBackgroundMiddle.mouseEnabled = false;
_layerBackgroundGround.mouseEnabled = false;
_layerBackgroundObstacle.mouseEnabled = false;
_layerBackgroundLauncher.mouseEnabled = false;
_guiLayer = new Sprite();
addChild(_layerBackgroundSky);
addChild(_layerBackgroundMiddle);
addChild(_layerBackgroundGround);
addChild(_layerBackgroundLauncher);
addChild(_layerBackgroundObstacle);
addChild(_layerPlayer);
addChild(_guiLayer);
loadScene("DistanceChallenge/room_main.xroom",_sounds);
_bInit = true;
}
else
{
startGame();
}
}
override protected function sceneLoaded(param1:Event) : void
{
var _loc4_:int = 0;
var _loc5_:Object = null;
var _loc3_:* = null;
SFX_ARM_GEARS = getDefinitionByName("gears") as Class;
if(SFX_ARM_GEARS == null)
{
throw new Error("Sound not found! name:gears");
}
SFX_ARM_WIND = getDefinitionByName("wind") as Class;
if(SFX_ARM_WIND == null)
{
throw new Error("Sound not found! name:wind");
}
_soundMan = new SoundManager(this);
loadSounds();
var _loc2_:int = 0;
if(_miniGameDefID != -1)
{
_loc2_ = MinigameManager.minigameInfoCache.getMinigameInfo(_miniGameDefID).lbUseVarRef;
}
if(_loc2_ != 0)
{
_recordDistance = Math.max(gMainFrame.userInfo.userVarCache.getUserVarValueById(_loc2_),0);
}
else
{
_recordDistance = 0;
}
_score = _scene.getLayer("score");
_guiLayer.addChild(_score.loader);
_score.loader.content.record.text = _recordDistance;
_loc5_ = _scene.getLayer("closeButton");
_closeBtn = addBtn("CloseButton",_loc5_.x,_loc5_.y,onCloseButton);
_launcher = _scene.getLayer("launcher");
_layerBackgroundLauncher.addChild(_launcher.loader);
_lastRot = _launcher.loader.content.stringAngle;
_backgroundElements = new Array(6);
_sky = [];
_sky.push(_scene.getLayer("sky"));
_sky.push(_scene.getLayer("sky_2"));
_sky[0].loader.y = 0;
_sky[1].loader.y = 0;
_loc4_ = 0;
while(_loc4_ < 6)
{
_backgroundElements[_loc4_] = {};
_backgroundElements[_loc4_].ground = [];
_backgroundElements[_loc4_].ground.push(_scene.getLayer("ground" + (_loc4_ + 1)));
_backgroundElements[_loc4_].ground.push(_scene.getLayer("ground" + (_loc4_ + 1) + "_2"));
_backgroundElements[_loc4_].ground[0].loader.y = _sky[0].height;
_backgroundElements[_loc4_].ground[1].loader.y = _sky[0].height;
_backgroundElements[_loc4_].obstacle = [];
_backgroundElements[_loc4_].obstacle.push(_scene.getLayer("obstacle" + (_loc4_ + 1)));
_backgroundElements[_loc4_].obstacle.push(_scene.getLayer("obstacle" + (_loc4_ + 1) + "_2"));
_backgroundElements[_loc4_].obstacle[0].loader.y = _sky[0].height;
_backgroundElements[_loc4_].obstacle[1].loader.y = _sky[0].height;
_backgroundElements[_loc4_].middle = [];
_backgroundElements[_loc4_].middle.push(_scene.getLayer("middle" + (_loc4_ + 1)));
_backgroundElements[_loc4_].middle.push(_scene.getLayer("middle" + (_loc4_ + 1) + "_2"));
_backgroundElements[_loc4_].middle[0].loader.y = _sky[0].height - _backgroundElements[_loc4_].middle[0].height;
_backgroundElements[_loc4_].middle[1].loader.y = _sky[0].height - _backgroundElements[_loc4_].middle[0].height;
_loc4_++;
}
_transition = _scene.getLayer("transition");
_transition.loader.y = _sky[0].height;
_sceneLoaded = true;
stage.addEventListener("enterFrame",heartbeat,false,0,true);
stage.addEventListener("mouseDown",mouseClickHandler);
stage.addEventListener("keyDown",fireKeyDown);
startGame();
super.sceneLoaded(param1);
}
public function message(param1:Array) : void
{
var _loc3_:int = 0;
var _loc2_:int = 0;
if(param1[0] != "ml")
{
if(param1[0] == "ms")
{
_dbIDs = [];
_loc2_ = 0;
while(_loc2_ < _pIDs.length)
{
_dbIDs[_loc2_] = param1[_loc2_ + 1];
_loc2_++;
}
}
else if(param1[0] == "mm")
{
}
}
}
private function fireKeyDown(param1:KeyboardEvent) : void
{
switch(param1.keyCode)
{
case 13:
case 32:
if(activeDlgMC == null)
{
mouseClickHandler(param1);
}
}
}
private function replayKeyDown(param1:KeyboardEvent) : void
{
switch(param1.keyCode)
{
case 13:
case 32:
onGreatJob_Yes();
break;
case 8:
case 46:
case 27:
onGreatJob_No();
}
}
private function greatJobKeyDown(param1:KeyboardEvent) : void
{
switch(param1.keyCode)
{
case 13:
case 32:
case 8:
case 46:
case 27:
showGreatJobDlg();
}
}
public function heartbeat(param1:Event) : void
{
var _loc8_:int = 0;
var _loc12_:Object = null;
var _loc6_:MovieClip = null;
var _loc4_:Number = NaN;
var _loc3_:int = 0;
var _loc9_:int = 0;
var _loc11_:Number = NaN;
var _loc2_:int = 0;
var _loc5_:Number = NaN;
var _loc7_:int = 0;
var _loc10_:int = 0;
if(_sceneLoaded)
{
_frameTime = (getTimer() - _lastTime) / 1000;
if(_frameTime > 0.5)
{
_frameTime = 0.5;
}
_lastTime = getTimer();
if(_displayAchievementTimer > 0)
{
_displayAchievementTimer -= _frameTime;
if(_displayAchievementTimer <= 0)
{
_displayAchievementTimer = 0;
AchievementManager.displayNewAchievements();
}
}
if(_sceneLoaded)
{
if(_player && _player._started == false && _launcher.loader.parent != null && _launcher.loader.content && _launcher.loader.content.launcherOn)
{
if(_gearsSound == null)
{
_gearsSound = _soundMan.play(SFX_ARM_GEARS,0,99999);
}
if(Math.abs(_launcher.loader.content.stringAngle - _lastRot) > 200)
{
_soundMan.playByName(_soundNameArmSwing);
}
_lastRot = _launcher.loader.content.stringAngle;
}
if(!_pauseGame)
{
_gameTime += _frameTime;
if(_gameOverTimer > 0)
{
_gameOverTimer -= _frameTime;
if(_gameOverTimer <= 0)
{
_closeBtn.visible = false;
stage.addEventListener("keyDown",greatJobKeyDown);
_loc6_ = showDlg("longshot_result",[{
"name":"continue_btn",
"f":showGreatJobDlg
}]);
_pauseGame = false;
_loc6_.x = 450;
_loc6_.y = 275;
_loc6_.result_score.text = valueTrackerCurrent();
_loc8_ = Math.random() * _facts.length;
_scene.getLayer(_facts[_loc8_].image).loader.x = 0;
_scene.getLayer(_facts[_loc8_].image).loader.y = 0;
_loc6_.result_pic.addChild(_scene.getLayer(_facts[_loc8_].image).loader);
LocalizationManager.updateToFit(_loc6_.result_fact,_facts[_loc8_].text);
_soundMan.playByName(_soundNameArmSuccess);
if(valueTrackerCurrent() > _recordDistance)
{
_recordDistance = valueTrackerCurrent();
_score.loader.content.record.text = _recordDistance;
valueTrackerCommit();
_displayAchievementTimer = 1;
}
}
}
_loc4_ = Math.max(_player._clone.loader.x,_loc9_);
_player.heartbeat(_frameTime);
updateWindVolume();
if(_player._started)
{
_loc3_ = 700;
_loc9_ = 50;
_loc11_ = (Math.min(_player._clone.loader.x,_loc3_) - _loc9_) / (_loc3_ - _loc9_);
_loc4_ = _player._clone.loader.x - _loc4_;
if(_loc4_ > 0)
{
_layerGroundMove += _loc4_ * _loc11_;
_loc2_ = _layerGroundMove;
if(_loc2_ > 0)
{
_layerGroundMove -= _loc2_;
_layerPlayer.x -= _loc2_;
_layerBackgroundGround.x -= _loc2_;
_layerBackgroundObstacle.x -= _loc2_;
_layerBackgroundLauncher.x -= _loc2_;
}
if(_launcher.loader.parent && _launcher.loader.x + _launcher.width + _layerBackgroundLauncher.x < 0)
{
_launcher.loader.parent.removeChild(_launcher.loader);
}
_layerSkyMove += _loc4_ * _loc11_ * 0.125;
_loc2_ = _layerSkyMove;
if(_loc2_ > 0)
{
_layerBackgroundSky.x -= _loc2_;
if(_layerBackgroundSky.x < -_sky[0].width)
{
_layerBackgroundSky.x += _sky[0].width;
}
_layerSkyMove -= _loc2_;
}
_loc8_ = _layerBackgroundGround.numChildren - 1;
while(_loc8_ >= 0)
{
_loc12_ = _layerBackgroundGround.getChildAt(_loc8_);
if(_loc12_.x + _loc12_.width + _layerBackgroundGround.x < 0)
{
if(_loc12_.x < _lastChangeBackgroundGroundX)
{
_loc12_.parent.removeChild(_loc12_);
_loc12_ = _layerBackgroundObstacle.getChildAt(_loc8_);
_loc12_.parent.removeChild(_loc12_);
}
else
{
_loc5_ = _addBackgroundGroundX;
_loc12_.x = _addBackgroundGroundX;
_addBackgroundGroundX += _loc12_.width;
_loc12_ = _layerBackgroundObstacle.getChildAt(_loc8_);
_loc12_.content.gotoAndPlay("off");
_loc12_.content.armadilloSpeedX = 0;
_loc12_.x = _loc5_ + _obstacleOffset;
}
}
_loc8_--;
}
if(_addBackgroundGroundX >= _nextBackgroundSwitch)
{
_loc7_ = 0;
_loc10_ = 1;
if(_nextBackgroundSwitch < 100800)
{
_loc7_ = 0;
_loc10_ = 1;
}
else if(_nextBackgroundSwitch <= 208800)
{
_loc7_ = 2;
_loc10_ = 3;
}
else
{
_loc7_ = 4;
_loc10_ = 5;
}
_loc8_ = _activeBackgroundType + 1;
if(_loc8_ > _loc10_ || _loc8_ < _loc7_)
{
_loc8_ = _loc7_;
}
setBackgroundActive(_loc8_);
}
_layerBackgroundMiddle.x = _layerBackgroundLauncher.x / 4;
_loc8_ = _layerBackgroundMiddle.numChildren - 1;
while(_loc8_ >= 0)
{
_loc12_ = _layerBackgroundMiddle.getChildAt(_loc8_);
if(_loc12_.x + _backgroundElements[0].ground[0].width * 2 + _layerBackgroundMiddle.x < 0)
{
if(_loc12_.x < _lastChangeMiddleX)
{
_loc12_.parent.removeChild(_loc12_);
}
else
{
_loc12_.x = _addMiddleX;
_loc12_.visible = false;
}
}
else if(_loc12_.visible == false)
{
if(_loc12_.x <= _lastChangeMiddleX)
{
_loc12_.parent.removeChild(_loc12_);
}
else if(_loc12_.x + _backgroundElements[0].ground[0].width * 2 + _layerBackgroundMiddle.x < _backgroundElements[0].ground[0].width * 2)
{
_addMiddleX += _backgroundElements[0].ground[0].width * 2;
_loc12_.visible = true;
}
}
_loc8_--;
}
}
if(_player._started)
{
_score.loader.content.distance.text = valueTrackerCurrent();
}
else
{
_score.loader.content.distance.text = 0;
}
}
if(_particles)
{
_loc8_ = _particles.length - 1;
while(_loc8_ >= 0)
{
_particles[_loc8_].timeRemaining -= _frameTime;
if(_particles[_loc8_].timeRemaining <= 0)
{
_particles[_loc8_].clone.loader.parent.removeChild(_particles[_loc8_].clone.loader);
_scene.releaseCloneAsset(_particles[_loc8_].clone.loader);
_particles.splice(_loc8_,1);
}
_loc8_--;
}
}
}
}
}
}
public function updateWindVolume() : void
{
var _loc1_:SoundTransform = null;
if(_windSound && !SBAudio.isMusicMuted)
{
_loc1_ = _windSound.soundTransform;
_loc1_.volume = Math.min(_player._velocity.x / 15000,0.2);
_windSound.soundTransform = _loc1_;
}
}
public function showGreatJobDlg() : void
{
stage.removeEventListener("keyDown",greatJobKeyDown);
stage.addEventListener("keyDown",replayKeyDown);
hideDlg();
var _loc1_:MovieClip = showDlg("card_longshot_greatjob",[{
"name":"button_yes",
"f":onGreatJob_Yes
},{
"name":"button_no",
"f":onGreatJob_No
}]);
_pauseGame = false;
_loc1_.x = 450;
_loc1_.y = 275;
LocalizationManager.translateIdAndInsert(_loc1_.text_score,_gemsEarned == 1 ? 11433 : 11432,_gemsEarned);
_loc1_.text_score.text.toLowerCase();
}
public function startGame() : void
{
if(_sceneLoaded)
{
_score.loader.content.distance.text = 0;
_gameOverTimer = 0;
resetGame();
_player = new DistanceChallengePlayer(this);
_obstacleOffset = 700;
_activeBackgroundType = -1;
_addBackgroundGroundX = 0;
_addMiddleX = 0;
_nextBackgroundSwitch = 0;
setBackgroundActive(0);
if(_launcher.loader.parent == null)
{
_layerBackgroundLauncher.addChild(_launcher.loader);
}
_launcher.loader.content.reset();
_soundMan.playByName(_soundNameArmIntro);
_gameTime = 0;
_lastTime = getTimer();
_frameTime = 0;
_layerBackgroundSky.x = 0;
_layerBackgroundGround.x = 0;
_layerBackgroundObstacle.x = 0;
_layerBackgroundLauncher.x = 0;
_layerBackgroundMiddle.x = 0;
_layerPlayer.x = 0;
_layerSkyMove = 0;
_layerGroundMove = 0;
}
}
public function resetGame() : void
{
var _loc1_:int = 0;
if(_windSound != null)
{
_windSound.stop();
_windSound = null;
}
if(_gearsSound != null)
{
_gearsSound.stop();
_gearsSound = null;
}
if(_particles)
{
while(_particles.length > 0)
{
_particles[0].clone.loader.parent.removeChild(_particles[0].clone.loader);
_scene.releaseCloneAsset(_particles[0].clone.loader);
_particles.splice(0,1);
}
}
if(_transition.loader.parent != null)
{
_transition.loader.parent.removeChild(_transition.loader);
}
_loc1_ = 0;
while(_loc1_ < 6)
{
if(_sky[0].loader.parent)
{
_sky[0].loader.parent.removeChild(_sky[0].loader);
}
if(_sky[1].loader.parent)
{
_sky[1].loader.parent.removeChild(_sky[1].loader);
}
if(_backgroundElements[_loc1_].ground[0].loader.parent)
{
_backgroundElements[_loc1_].ground[0].loader.parent.removeChild(_backgroundElements[_loc1_].ground[0].loader);
}
if(_backgroundElements[_loc1_].ground[1].loader.parent)
{
_backgroundElements[_loc1_].ground[1].loader.parent.removeChild(_backgroundElements[_loc1_].ground[1].loader);
}
if(_backgroundElements[_loc1_].obstacle[0].loader.parent)
{
_backgroundElements[_loc1_].obstacle[0].loader.parent.removeChild(_backgroundElements[_loc1_].obstacle[0].loader);
}
if(_backgroundElements[_loc1_].obstacle[1].loader.parent)
{
_backgroundElements[_loc1_].obstacle[1].loader.parent.removeChild(_backgroundElements[_loc1_].obstacle[1].loader);
}
if(_backgroundElements[_loc1_].middle[0].loader.parent)
{
_backgroundElements[_loc1_].middle[0].loader.parent.removeChild(_backgroundElements[_loc1_].middle[0].loader);
}
if(_backgroundElements[_loc1_].middle[1].loader.parent)
{
_backgroundElements[_loc1_].middle[1].loader.parent.removeChild(_backgroundElements[_loc1_].middle[1].loader);
}
_loc1_++;
}
if(_player)
{
_player.remove();
_player = null;
}
}
public function setBackgroundActive(param1:int) : void
{
if(_activeBackgroundType != param1)
{
if(_addBackgroundGroundX > 0)
{
_transition.loader.x = _addBackgroundGroundX - _transition.width / 2;
if(_transition.loader.parent == null)
{
_layerBackgroundLauncher.addChild(_transition.loader);
}
}
_addMiddleX = _addBackgroundGroundX / 4 + 1;
if(_addMiddleX > 1 && _addMiddleX + _layerBackgroundMiddle.x < 900)
{
_addMiddleX = 900 - _layerBackgroundMiddle.x;
}
_lastChangeBackgroundGroundX = _addBackgroundGroundX;
_lastChangeMiddleX = _addMiddleX;
if(_sky[0].loader.parent == null)
{
_layerBackgroundSky.addChild(_sky[0].loader);
_sky[0].loader.x = 0;
_layerBackgroundSky.addChild(_sky[1].loader);
_sky[1].loader.x = _sky[0].width;
}
_layerBackgroundGround.addChild(_backgroundElements[param1].ground[0].loader);
_layerBackgroundObstacle.addChild(_backgroundElements[param1].obstacle[0].loader);
_layerBackgroundMiddle.addChild(_backgroundElements[param1].middle[0].loader);
_layerBackgroundGround.addChild(_backgroundElements[param1].ground[1].loader);
_layerBackgroundObstacle.addChild(_backgroundElements[param1].obstacle[1].loader);
_backgroundElements[param1].obstacle[0].loader.content.gotoAndPlay("off");
_backgroundElements[param1].obstacle[1].loader.content.gotoAndPlay("off");
_backgroundElements[param1].obstacle[0].loader.content.armadilloSpeedX = 0;
_backgroundElements[param1].middle[0].loader.visible = true;
_backgroundElements[param1].ground[0].loader.x = _addBackgroundGroundX;
_backgroundElements[param1].obstacle[0].loader.x = _addBackgroundGroundX + _obstacleOffset;
_backgroundElements[param1].middle[0].loader.x = _addMiddleX;
_addBackgroundGroundX += _backgroundElements[param1].ground[0].width;
_addMiddleX += _backgroundElements[param1].ground[0].width * 2;
_backgroundElements[param1].obstacle[1].loader.content.armadilloSpeedX = 0;
_backgroundElements[param1].ground[1].loader.x = _addBackgroundGroundX;
_backgroundElements[param1].obstacle[1].loader.x = _addBackgroundGroundX + _obstacleOffset;
_addBackgroundGroundX += _backgroundElements[param1].ground[0].width;
_addMiddleX += _backgroundElements[param1].ground[0].width * 2;
_activeBackgroundType = param1;
_nextBackgroundSwitch += 7200;
}
}
public function setGameOver() : void
{
var _loc2_:int = 0;
var _loc3_:Array = new Array(1000,2000,3000,4000,5000,8000,10000,15000,20000,25000,30000,40000,50000,60000,75000,100000,150000);
var _loc1_:Array = new Array(1,2,4,6,8,10,15,20,25,35,50,75,100,125,150,200,250);
_gemsEarned = 300;
_loc2_ = 0;
while(_loc2_ < _loc3_.length)
{
if(valueTrackerCurrent() < _loc3_[_loc2_])
{
_gemsEarned = _loc1_[_loc2_];
break;
}
_loc2_++;
}
addGemsToBalance(_gemsEarned);
_gameOverTimer = 2;
}
public function addSnowmanHead(param1:Number, param2:Number) : void
{
var _loc3_:Object = null;
if(_particles)
{
_loc3_ = {};
_loc3_.clone = _scene.cloneAsset("snowmanHead");
// the winter snowman is not in every season's scene (#1009)
if(_loc3_.clone == null)
{
return;
}
_loc3_.clone.loader.x = _layerBackgroundGround.x + param1;
_loc3_.clone.loader.y = param2;
_loc3_.clone.loader.contentLoaderInfo.addEventListener("complete",onSnowmanLoad);
_loc3_.timeRemaining = 5;
addChild(_loc3_.clone.loader);
_particles.push(_loc3_);
}
}
public function onSnowmanLoad(param1:Event) : void
{
param1.target.content.hit(_player._velocity.x,_player._velocity.y);
param1.target.removeEventListener("complete",onSnowmanLoad);
}
private function mouseClickHandler(param1:Event) : void
{
if(_sceneLoaded)
{
if(_player)
{
if(!_player._started)
{
if(_launcher.loader.content.launcherOn)
{
_launcher.loader.content.launch();
_player.start();
if(_windSound == null)
{
_windSound = _soundMan.play(SFX_ARM_WIND,0,99999);
if(_gearsSound != null)
{
_gearsSound.stop();
_gearsSound = null;
}
}
}
}
}
}
}
private function onCloseButton() : void
{
var _loc1_:MovieClip = showDlg("ExitConfirmationDlg",[{
"name":"button_yes",
"f":onExit_Yes
},{
"name":"button_no",
"f":onExit_No
}]);
_loc1_.x = 450;
_loc1_.y = 275;
}
private function onExit_Yes() : void
{
hideDlg();
if(showGemMultiplierDlg(onGemMultiplierDone) == null)
{
end(null);
}
}
private function onGemMultiplierDone() : void
{
hideDlg();
end(null);
}
private function onExit_No() : void
{
hideDlg();
}
private function onGreatJob_Yes() : void
{
stage.removeEventListener("keyDown",replayKeyDown);
if(MinigameManager.minigameInfoCache && MinigameManager.minigameInfoCache.currMinigameId != -1)
{
AchievementXtCommManager.requestSetUserVar(MinigameManager.minigameInfoCache.getMinigameInfo(MinigameManager.minigameInfoCache.currMinigameId).gameCountUserVarRef,1);
_displayAchievementTimer = 1;
}
_closeBtn.visible = true;
hideDlg();
startGame();
}
private function onGreatJob_No() : void
{
stage.removeEventListener("keyDown",replayKeyDown);
hideDlg();
if(showGemMultiplierDlg(onGemMultiplierDone) == null)
{
end(null);
}
}
}
}
+602
View File
@@ -0,0 +1,602 @@
package ecard
{
import den.DenXtCommManager;
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFormat;
import loader.MediaHelper;
import localization.LocalizationManager;
public class ECard
{
public static const TYPE_STANDARD:int = 0;
public static const TYPE_CLOTHING:int = 1;
public static const TYPE_BUDDY:int = 2;
public static const TYPE_DEN_ACC:int = 3;
public static const TYPE_GEMS:int = 4;
public static const TYPE_DEN_ROOM:int = 5;
public static const TYPE_AVT:int = 6;
public static const TYPE_SUBSCRIPTION:int = 7;
public static const TYPE_PET:int = 8;
public static const TYPE_DIAMOND:int = 9;
public static const TYPE_CUSTOM_AVT:int = 10;
public static const TYPE_EMAIL_RESET:int = 11;
public static const TYPE_ADOPT_A_PET:int = 12;
public static const TYPE_PROMOTION:int = 13;
public static const TYPE_DEN_AUDIO:int = 99;
public static const CARD_ID_REDEMPTION:int = 0;
public static const CARD_ID_BULK:int = -1;
public static const ECARD_REDEMPTION_STAMP_NORMAL:int = 0;
public static const ECARD_REDEMPTION_STAMP_AJJUMP:int = 1;
public static const ECARD_REDEMPTION_STAMP_DIAMOND_REFUND:int = 2;
public static const ECARD_REDEMPTION_STAMP_REFERRAL:int = 3;
public static const MESSAGE_TYPE_BUBBLECHAT:int = 1;
public static const MESSAGE_TYPE_LIMITEDCHAT:int = 2;
public static const SENDER_USER:int = 0;
public static const SENDER_VOICE:int = 1;
public static const SENDER_REDEM:int = 2;
public static const SPECIAL_TYPE_NORMAL:int = 0;
public static const SPECIAL_TYPE_VALENTINES:int = 1;
private var _msgId:int;
private var _senderUserName:String;
private var _cardMediaId:int;
private var _stampMediaId:int;
private var _isRead:Boolean;
private var _msg:String;
private var _type:int;
private var _secondaryType:int;
private var _giftId:int;
private var _giftColor:uint;
private var _giftName:String;
private var _senderType:int;
private var _senderSGAccountType:int;
private var _senderNameBarData:int;
private var _userNameModerationFlag:int;
private var _messageTxt:TextField;
private var _stampCont:MovieClip;
private var _isReadInProcess:Boolean;
private var _additionalGiftData:String;
private var _specialType:int;
private var _cardImg:MovieClip;
private var _cardImgHelper:MediaHelper;
private var _stampImg:MovieClip;
private var _stampImgHelper:MediaHelper;
private var _acceptBtn:MovieClip;
private var _rejectBtn:MovieClip;
private var _memberNameBar:MovieClip;
private var _nonMemberNameBar:MovieClip;
private var _nonMemberUserName:TextField;
private var _charBox:MovieClip;
private var _linkToBtn:MovieClip;
private var _changeEmailBtn:MovieClip;
private var _cancelEmailBtn:MovieClip;
private var _buttonsLoadedCallback:Function;
public function ECard()
{
super();
}
public function init(param1:int, param2:String, param3:int, param4:int, param5:Boolean, param6:String, param7:int, param8:int, param9:uint, param10:String, param11:int, param12:int, param13:int, param14:int, param15:int, param16:String, param17:int) : void
{
_msgId = param1;
_senderUserName = param2;
_cardMediaId = param3;
_stampMediaId = param4;
_isRead = param5;
_msg = param6;
_type = param7;
_giftId = param8;
_giftColor = param9;
_giftName = param10;
_senderSGAccountType = param11;
_senderNameBarData = param12;
_secondaryType = param13;
_senderType = param14;
_userNameModerationFlag = param15;
_additionalGiftData = param16;
_specialType = param17;
if(param7 == 3 && DenXtCommManager.getDenItemDef(_giftId) != null)
{
if(DenXtCommManager.getDenItemDef(_giftId).sortCat == 4)
{
_type = 99;
}
}
else if(param7 == 0 && _giftId > 0)
{
_giftId = 0;
}
if(param17 == 1)
{
_senderUserName = LocalizationManager.translateIdOnly(32191);
}
else if(isFromVoice)
{
_senderUserName = LocalizationManager.translateIdOnly(int(_senderUserName));
}
_stampImg = new MovieClip();
_cardImg = new MovieClip();
}
public function get msgId() : int
{
return _msgId;
}
public function get senderUserName() : String
{
return _senderUserName;
}
public function get senderModeratedUserName() : String
{
if(_specialType == 1 || _userNameModerationFlag > 0)
{
return _senderUserName;
}
return LocalizationManager.translateIdOnly(11098);
}
public function get cardMediaId() : int
{
return _cardMediaId;
}
public function get stampMediaId() : int
{
return _stampMediaId;
}
public function get isRead() : Boolean
{
return _isRead;
}
public function set isRead(param1:Boolean) : void
{
_isRead = param1;
}
public function get msg() : String
{
return _msg;
}
public function set msg(param1:String) : void
{
_msg = param1;
}
public function get modifiedMsg() : String
{
var _loc1_:String = null;
if(_msg == "")
{
if(_cardImg.numChildren == 0)
{
cardImg;
}
return "";
}
if(isFromVoice)
{
if(_type == 11)
{
return LocalizationManager.translateIdOnly(24440);
}
if(isNaN(parseInt(_msg)))
{
return _msg;
}
_loc1_ = LocalizationManager.translateIdOnly(parseInt(_msg));
if(_loc1_.indexOf("%s") == -1)
{
return _loc1_;
}
return LocalizationManager.translateIdAndInsertOnly(parseInt(_msg),_additionalGiftData);
}
// the game swapped any message with a word outside its approved
// list for "Animal Jam rocks!" (28985) when showing it; typing is
// free here (gui.ECardCreation), so the words are shown as sent
return _msg;
}
public function get isBuddy() : Boolean
{
return _type == 2;
}
public function get isGift() : Boolean
{
return (_type == 1 || _type >= 3) && _type != 11;
}
public function get isEmailReset() : Boolean
{
return _type == 11;
}
public function get giftId() : int
{
return _giftId;
}
public function get giftColor() : uint
{
return _giftColor;
}
public function get giftName() : String
{
return _giftName;
}
public function set giftName(param1:String) : void
{
_giftName = param1;
}
public function get isSenderMember() : Boolean
{
return _senderSGAccountType >= 2;
}
public function get isSenderArchived() : Boolean
{
return _senderSGAccountType == -2;
}
public function get senderSGAccountType() : int
{
return _senderSGAccountType;
}
public function get isFromUser() : Boolean
{
return _senderType == 0;
}
public function get isFromVoice() : Boolean
{
return _senderType == 1;
}
public function get isStartupJAG() : Boolean
{
return _senderType == 2 || !gMainFrame.userInfo.isMember && isAJHQGift || _cardMediaId == -1;
}
public function get isRedemptionJAG() : Boolean
{
if(isStartupJAG && (giftId > 0 || type == 4 || type == 7 || type == 13 || type == 9))
{
return true;
}
return false;
}
public function get isAJHQGift() : Boolean
{
return isFromVoice && _giftId > 0;
}
public function get isBulkItem() : Boolean
{
return _cardMediaId == -1;
}
public function get type() : int
{
return _type;
}
public function set type(param1:int) : void
{
_type = param1;
}
public function get secondaryType() : int
{
return _secondaryType;
}
public function get nameBarData() : int
{
return _senderNameBarData;
}
public function set nameBarData(param1:int) : void
{
_senderNameBarData = param1;
}
public function get cardImg() : MovieClip
{
if(_cardImg.numChildren == 0)
{
if(_cardImgHelper == null)
{
_cardImgHelper = new MediaHelper();
_cardImgHelper.init(_cardMediaId,cardImgReceived);
}
}
else
{
ECardManager.onECardLoaded(this);
}
return _cardImg;
}
public function get stampImg() : MovieClip
{
if(_type != 2 && !isFromVoice)
{
if(_stampImg.numChildren == 0)
{
_stampImgHelper = new MediaHelper();
_stampImgHelper.init(_stampMediaId,stampImgReceived);
}
}
return _stampImg;
}
public function get acceptBtn() : MovieClip
{
return _acceptBtn;
}
public function get rejectBtn() : MovieClip
{
return _rejectBtn;
}
public function get memberNameBar() : MovieClip
{
return _memberNameBar;
}
public function get nonMemberNameBar() : MovieClip
{
return _nonMemberNameBar;
}
public function get nonMemberUserName() : TextField
{
return _nonMemberUserName;
}
public function get charBox() : MovieClip
{
return _charBox;
}
public function get changeEmailBtn() : MovieClip
{
return _changeEmailBtn;
}
public function get cancelEmailBtn() : MovieClip
{
return _cancelEmailBtn;
}
public function get messageTxt() : TextField
{
return _messageTxt;
}
public function get stampCont() : MovieClip
{
return _stampCont;
}
public function get isReadInProcess() : Boolean
{
return _isReadInProcess;
}
public function set isReadInProcess(param1:Boolean) : void
{
_isReadInProcess = param1;
}
public function get additionalGiftData() : String
{
return _additionalGiftData;
}
public function get linkToBtn() : MovieClip
{
return _linkToBtn;
}
public function get specialType() : int
{
return _specialType;
}
private function cardImgReceived(param1:MovieClip) : void
{
var _loc3_:TextFormat = null;
var _loc2_:MovieClip = param1.getChildAt(0) as MovieClip;
if(_loc2_)
{
param1 = _loc2_;
}
_cardImg.addChild(param1);
if(param1.userNameTxt)
{
param1.userNameTxt.text = _senderUserName;
}
if(param1.msgTxt)
{
_messageTxt = param1.msgTxt;
if(modifiedMsg == "")
{
_msg = _messageTxt.text;
}
if(isFromUser)
{
if(modifiedMsg != "")
{
_messageTxt.text = modifiedMsg;
}
_loc3_ = _messageTxt.getTextFormat();
_loc3_.size = 50;
_messageTxt.setTextFormat(_loc3_);
if(_messageTxt.textHeight / Number(_messageTxt.getTextFormat().size) > 1 || _messageTxt.textHeight / 50 > 1)
{
_loc3_.size = 30;
_messageTxt.setTextFormat(_loc3_);
if(_messageTxt.textHeight / Number(_messageTxt.getTextFormat().size) < 1)
{
_messageTxt.y += 13;
}
}
else
{
_messageTxt.setTextFormat(_loc3_);
}
}
else if(modifiedMsg != "" && _type != 11)
{
LocalizationManager.updateToFit(_messageTxt,modifiedMsg);
}
}
else if(isFromUser)
{
_msg = LocalizationManager.translateIdOnly(28985);
}
else
{
_msg = LocalizationManager.translateIdOnly(24440);
}
if(param1.stamp)
{
_stampCont = param1.stamp;
_stampCont.addChild(stampImg);
}
if(_type == 2)
{
if(param1.okBtn)
{
_acceptBtn = param1.okBtn;
}
if(param1.cancelBtn)
{
_rejectBtn = param1.cancelBtn;
}
if(param1.member)
{
_memberNameBar = param1.member;
}
if(param1.nonmember)
{
_nonMemberNameBar = param1.nonmember;
}
if(param1.userName_txt)
{
_nonMemberUserName = param1.userName_txt;
}
if(param1.charBox)
{
_charBox = param1.charBox;
}
}
else if(_type == 11)
{
if(param1.changeEmailBtn)
{
_changeEmailBtn = param1.changeEmailBtn;
}
if(param1.cancelBtn)
{
_cancelEmailBtn = param1.cancelBtn;
}
}
if((_cardMediaId == 1194 || _cardMediaId == 1630) && _msg != "")
{
if(param1.hasOwnProperty("txt"))
{
param1.txt.text = "";
}
}
if(param1.linkTo)
{
_linkToBtn = param1.linkTo;
}
ECardManager.onECardLoaded(this);
_cardImgHelper.destroy();
_cardImgHelper = null;
}
private function stampImgReceived(param1:MovieClip) : void
{
_stampImg.addChild(param1);
}
}
}
File diff suppressed because it is too large. Load diff
+231
View File
@@ -0,0 +1,231 @@
package gui
{
import collection.StreamDefCollection;
import movie.MovieManager;
import quest.QuestManager;
import room.RoomManagerWorld;
import shop.ShopManager;
public class GenericListGuiManager
{
public static var movieSelector:MovieManager;
public function GenericListGuiManager()
{
super();
}
public static function genericListVolumeClicked(param1:int, param2:Object = null) : void
{
var _loc3_:int = int(gMainFrame.userInfo.getGenericListDefByDefId(param1).typeId);
switch(_loc3_)
{
case 1000:
case 1030:
case 1051:
case 1054:
case 1060:
if(!RoomManagerWorld.instance.inPreviewMode && (param2 == null || !param2.hasOwnProperty("volName") || QuestManager.onShopClick(param2.volName)))
{
ShopManager.launchStore(param1,_loc3_);
}
break;
case 1040:
GuiManager.openDenRoomSwitcher(false,null,true,-1,param1);
break;
case 1037:
DarkenManager.showLoadingSpiral(true);
GenericListXtCommManager.requestStreamList(param1,launchMovies,param2);
break;
case 1023:
case 1033:
case 1035:
}
}
public static function launchMovies(param1:int, param2:StreamDefCollection, param3:Object = null) : void
{
var _loc5_:Array = null;
var _loc4_:Boolean = false;
// the video lists came from the official server; this one answers
// them empty, and a player with nothing to play threw (#1009 in
// VideoPlayerOSMF.playNonStreaming)
if(param2 == null || param2.length == 0)
{
DarkenManager.showLoadingSpiral(false);
return;
}
if(param2.length > 1)
{
GenericListXtCommManager.filterTypedItems(param2);
if(movieSelector && RoomManagerWorld.instance.theaterWindow)
{
DarkenManager.showLoadingSpiral(false);
movieSelector.toggleVisibility();
}
else
{
if(movieSelector)
{
movieSelector.destroy();
movieSelector = null;
}
movieSelector = new MovieManager();
movieSelector.init(GuiManager.guiLayer,RoomManagerWorld.instance.theaterWindow,param2,202,39,onMovieSelectorClose);
if(param3)
{
movieSelector.setSkinFrame(frameIdForMsg(param3.msg));
movieSelector.setVideoFrameId(videoPlayerFrameIdForMsg(param3.msg));
if(param3.msg == "bb" || param3.msg == "tt" || param3.msg == "cami" || param3.msg == "gw")
{
movieSelector.setQuestionBtn();
}
if(param3.titleTxt)
{
movieSelector.setTitleTxt(param3.titleTxt);
}
if(param3.msg.indexOf("autoplay") != -1)
{
movieSelector.chooseRandom(true,videoPlayerFrameIdForMsg(param3.msg),param3.shouldRepeat != null ? param3.shouldRepeat : false);
}
if(param3.shouldRepeat != null)
{
movieSelector.setShouldRepeat(param3.shouldRepeat);
}
if(param3.width && param3.height)
{
movieSelector.setDefaultWidthHeight(param3.width,param3.height);
}
}
}
}
else if(param3)
{
if(param3.msg)
{
_loc5_ = param3.msg.split("%");
if(_loc5_.length > 1)
{
param3.shouldRepeat = _loc5_[1] == "true";
param3.width = int(_loc5_[2]);
param3.height = int(_loc5_[3]);
}
}
_loc4_ = true;
if(param3.shouldRepeat != null)
{
_loc4_ = Boolean(param3.shouldRepeat);
}
if(param3.width && param3.height)
{
GuiManager.initMoviePlayer(39,param2,_loc4_,param3.width,param3.height);
}
else
{
GuiManager.initMoviePlayer(39,param2,_loc4_);
}
if(_loc5_)
{
GuiManager.setVideoPlayerSkin(videoPlayerFrameIdForMsg(_loc5_[0]));
}
}
else
{
GuiManager.initMoviePlayer(39,param2,false);
}
}
public static function onRoomExit() : void
{
if(movieSelector)
{
movieSelector.destroy();
movieSelector = null;
}
}
public static function togglePlayPauseVideoPlayer(param1:Boolean) : void
{
if(movieSelector)
{
movieSelector.togglePlayPauseVideoPlayer(param1);
}
}
private static function frameIdForMsg(param1:String) : int
{
if(param1)
{
param1 = param1.toLowerCase();
}
else
{
param1 = "";
}
if(param1 == "bb" || param1 == "bb_experiments")
{
return 2;
}
if(param1 == "tt" || param1 == "tt_autoplay")
{
return 3;
}
if(param1 == "cami")
{
return 4;
}
if(param1 == "gw")
{
return 5;
}
return 1;
}
private static function videoPlayerFrameIdForMsg(param1:String) : int
{
if(param1)
{
param1 = param1.toLowerCase();
}
else
{
param1 = "";
}
if(param1 == "bb" || param1 == "bb_experiments")
{
return 2;
}
if(param1 == "tt" || param1 == "tt_autoplay")
{
return 3;
}
if(param1 == "biggerframe")
{
return 6;
}
if(param1 == "cami")
{
return 4;
}
if(param1 == "gw")
{
return 5;
}
return 1;
}
private static function onMovieSelectorClose() : void
{
if(movieSelector)
{
movieSelector.toggleVisibility();
}
}
public function init() : void
{
}
}
}
+3710 -3709
View File
File diff suppressed because it is too large. Load diff
+830
View File
@@ -0,0 +1,830 @@
package com.sbi.graphics
{
import com.sbi.corelib.Set;
import com.sbi.corelib.audio.SBAudio;
import com.sbi.loader.ImageServerEvent;
import com.sbi.loader.ImageServerURL;
import flash.geom.Matrix;
import flash.geom.Point;
public class LayerAnim
{
public static const PLAY_LOOP:int = 0;
public static const PLAY_ONE_SHOT:int = 1;
public static const PLAY_LOOP__KEEP_CURRENT_FRAME:int = 2;
public static const PLAY_FRAME:int = 3;
public static const AN_SIT_NNE:int = 1;
public static const AN_SIT_NE:int = 2;
public static const AN_SIT_E:int = 3;
public static const AN_SIT_SE:int = 4;
public static const AN_SIT_SSE:int = 5;
public static const AN_MOVE_NNE:int = 7;
public static const AN_MOVE_NE:int = 8;
public static const AN_MOVE_E:int = 9;
public static const AN_MOVE_SE:int = 10;
public static const AN_MOVE_SSE:int = 11;
public static const AN_BBCARD:int = 13;
public static const AN_IDLE_SE:int = 14;
public static const AN_HUD_AVT:int = 15;
public static const AN_IDLE_NE:int = 16;
public static const AN_HOP:int = 17;
public static const AN_SLEEP:int = 22;
public static const AN_DANCE:int = 23;
public static const AN_PLAY:int = 6;
public static const AN_LEAP:int = 35;
public static const AN_JUMP_EAST:int = 34;
public static const AN_SWIM_N:int = 36;
public static const AN_SWIM_NE:int = 34;
public static const AN_SWIM_E:int = 29;
public static const AN_SWIM_SE:int = 35;
public static const AN_SWIM_S:int = 37;
public static const AN_FLOAT:int = 32;
public static const AN_WATER_DIVE:int = 41;
public static const AN_WATER_PLAY:int = 39;
public static const AN_WATER_SPIN:int = 33;
public static const AN_WATER_JIG:int = 38;
public static const AN_WATER_POSE:int = 40;
public static const AN_PHOTO:int = 42;
public static const AN_PARACHUTE_IDLE:int = 19;
public static const AN_PARACHUTE_JUMP:int = 24;
public static const AN_PARACHUTE_DISTRESS:int = 20;
public static const AN_PARACHUTE_LAND:int = 21;
public static const AN_WINDRIDER_JUMP:int = 28;
public static const AN_WINDRIDER_IDLE:int = 29;
public static const AN_WINDRIDER_FALL:int = 30;
public static const AN_WINDRIDER_START:int = 31;
public static const AN_WINDRIDER_DISTRESS:int = 20;
public static const AVATAR_BITMAP_OFFSET_X:int = 375;
public static const AVATAR_BITMAP_OFFSET_Y:int = 365;
private static var _activePool:Vector.<LayerAnim>;
private static var _avOffsets:Array;
private static var _throttle:int = 8;
private static var _lastEntry:int;
private static var _useMaxThrottle:Function;
// variables holding functions (the game sets them through isOnscreen and
// hasSequence), which the decompiler shows as functions: compiled as
// functions they cannot be assigned (#1037 at startup)
private static var _isOnscreen:Function = function(param1:LayerAnim):Boolean
{
return true;
};
private static var _hasSequence:Function = function(param1:int):Boolean
{
return true;
};
private var _bitmap:LayerBitmap;
private var _avDefId:int;
private var _animId:int;
private var _frame:int;
private var _hFlip:Boolean;
private var _totalFrames:int;
private var _lastAnchorPoint:Point;
private var _x:int;
private var _y:int;
private var _rotation:int;
private var _xOff:int;
private var _yOff:int;
private var _bReposition:Boolean;
private var _bPause:Boolean;
private var _layers:Array;
private var _colors:Array;
private var _callback:Function;
private var _mode:int;
private var _tStep:int;
private var _bReload:Boolean;
private var _avatarEnabled:Boolean = true;
private var _requestAnimId:int;
private var _receivedData:Array;
// each requested image's place in _layers: items worn in the same
// slot are drawn in that order, the later over the earlier
private var _order:Object;
private var _requestedIds:Set;
private var _requestedCacheKey:String;
private var _requestCallback:Function;
private var _requestMode:int;
private var _preloadRequestedIds:Set;
private var _preloadCallback:Function;
private var _bounceEnabled:Boolean;
private var _bounceOverride:Boolean;
private var _bounceOffSet:int;
private var _local:Boolean;
private var _skipWorldCheck:Boolean;
public function LayerAnim(param1:Class)
{
super();
if(param1 != SingletonLock)
{
throw new Error("Invalid access. Use LayerAnim.getNew");
}
}
public static function set avOffsets(param1:Array) : void
{
_avOffsets = param1;
}
public static function getAvOffset(param1:int) : Point
{
if(_avOffsets[param1])
{
return _avOffsets[param1];
}
return new Point(-100,-100);
}
public static function set throttle(param1:int) : void
{
_throttle = param1;
}
public static function getNew(param1:Boolean = false) : LayerAnim
{
if(!_activePool)
{
_activePool = new Vector.<LayerAnim>();
}
var _loc2_:LayerAnim = new LayerAnim(SingletonLock);
_activePool.push(_loc2_);
_loc2_.init(param1);
return _loc2_;
}
public static function destroy(param1:LayerAnim) : void
{
var _loc2_:int = _activePool.indexOf(param1);
if(_loc2_ >= 0)
{
_activePool.splice(_loc2_,1);
if(_loc2_ > 0 && _lastEntry >= _loc2_)
{
_lastEntry = _lastEntry - 1;
}
param1.destroy();
}
}
public static function heartbeat() : void
{
var _loc2_:int = 0;
var _loc4_:int = 0;
var _loc1_:int = 0;
var _loc5_:int = 0;
if(_activePool && _activePool.length)
{
_loc2_ = int(_activePool.length);
_loc4_ = _loc2_;
_loc1_ = _loc2_ * 0.5;
if(_loc1_ < 1 || _useMaxThrottle && _useMaxThrottle())
{
_loc1_ = 1;
}
if(_loc1_ > _throttle)
{
_loc1_ = _throttle;
}
_loc5_ = _lastEntry;
for each(var _loc3_:LayerAnim in _activePool)
{
_loc3_._tStep++;
}
while(_loc1_ > 0 && _loc4_ > 0)
{
if(_loc5_ >= _loc2_)
{
_loc5_ = 0;
}
_loc3_ = _activePool[_loc5_++];
if(_loc3_._tStep >= 2)
{
_loc3_._tStep = 0;
if((_loc3_._requestMode == 1 || _isOnscreen(_loc3_) || _loc3_._skipWorldCheck) && _loc3_.heartbeat())
{
_loc1_--;
}
}
_loc4_--;
}
_lastEntry = _loc5_;
}
}
public static function set useMaxThrottle(param1:Function) : void
{
_useMaxThrottle = param1;
}
public static function set isOnscreen(param1:Function) : void
{
if(param1 != null)
{
_isOnscreen = param1;
}
}
public static function set hasSequence(param1:Function) : void
{
if(param1 != null)
{
_hasSequence = param1;
}
}
public static function trimAnims() : Set
{
var _loc2_:Set = new Set();
if(_activePool && _activePool.length)
{
for each(var _loc1_:LayerAnim in _activePool)
{
_loc2_.addAll(_loc1_.bitmap.trimLayerGroups());
}
}
return _loc2_;
}
public function get bounceOffSet() : int
{
return _bounceOffSet;
}
public function get bounceEnabled() : Boolean
{
return _bounceEnabled;
}
public function set bounceEnabled(param1:Boolean) : void
{
_bounceEnabled = param1;
}
public function set local(param1:Boolean) : void
{
_local = param1;
}
private function init(param1:Boolean = false) : void
{
_bitmap = new LayerBitmap();
_bitmap.pixelSnapping = "always";
_layers = null;
_requestAnimId = -1;
_avDefId = -1;
_animId = -1;
_totalFrames = 0;
_lastAnchorPoint = new Point(0,0);
_bReposition = true;
_bReload = true;
_tStep = 1;
_bounceEnabled = false;
_avatarEnabled = true;
_skipWorldCheck = param1;
_preloadRequestedIds = new Set();
_requestedIds = new Set();
}
private function destroy() : void
{
if(_bitmap)
{
_bitmap.destroy();
_bitmap = null;
}
ImageServerURL.instance.removeEventListener("OnNewData",onReceiveData);
_layers = null;
_callback = null;
_preloadRequestedIds.clear();
_requestedIds.clear();
}
public function set avDefId(param1:int) : void
{
if(param1 != _avDefId)
{
_avDefId = param1;
_xOff = -getAvOffset(_avDefId).x - 375;
_yOff = -getAvOffset(_avDefId).y - 365;
_bReposition = true;
_bReload = true;
}
}
public function get layers() : Array
{
return _layers;
}
public function get avDefId() : int
{
return _avDefId;
}
public function get animId() : int
{
return _animId;
}
public function get hFlip() : Boolean
{
return _hFlip;
}
public function get frame() : int
{
return _frame;
}
public function set frame(param1:int) : void
{
_frame = param1;
}
public function set avatarEnabled(param1:Boolean) : void
{
_avatarEnabled = param1;
}
public function set layers(param1:Array) : void
{
var _loc2_:Boolean = true;
var _loc3_:Boolean = false;
if(_layers && _layers.length == param1.length)
{
_loc2_ = false;
for(var _loc4_ in param1)
{
if(!_layers[_loc4_] || _layers[_loc4_].l != param1[_loc4_].l)
{
_loc2_ = true;
break;
}
if(_layers[_loc4_].c != param1[_loc4_].c)
{
_loc3_ = true;
}
}
if(!_loc2_ && !_loc3_)
{
return;
}
}
if(param1.length > 0)
{
_layers = param1;
if(_loc2_)
{
_bReload = true;
}
else if(_loc3_)
{
var _loc6_:Object = {};
for each(var _loc5_:Object in param1)
{
var _loc7_:int = ImageServerURL.instance.getLayerIndex(_loc5_.l);
var _loc8_:int = int(_loc6_[_loc7_]);
_loc6_[_loc7_] = _loc8_ + 1;
_bitmap.setLayerColor(LayerBitmap.slotFor(_loc7_,_loc8_),_loc5_.c);
}
}
}
}
public function get x() : int
{
return _x;
}
public function get y() : int
{
return _y;
}
public function set x(param1:int) : void
{
if(_x != param1)
{
_x = param1;
_bReposition = true;
}
}
public function set y(param1:int) : void
{
if(_y != param1)
{
_y = param1;
_bReposition = true;
}
}
public function set alpha(param1:Number) : void
{
_bitmap.alpha = param1;
}
public function set rotation(param1:Number) : void
{
if(_rotation != param1)
{
_rotation = param1;
_bReposition = true;
}
}
public function set hFlip(param1:Boolean) : void
{
if(param1 != _hFlip)
{
_hFlip = param1;
}
}
public function set visible(param1:Boolean) : void
{
_bitmap.visible = param1;
}
public function get visible() : Boolean
{
return _bitmap.visible;
}
public function set pause(param1:Boolean) : void
{
_bPause = param1;
}
public function get bitmap() : LayerBitmap
{
return _bitmap;
}
public function playAnim(param1:int, param2:int = 0, param3:Function = null, param4:int = 0) : void
{
if(_requestAnimId == -1 && param1 != _animId || _requestAnimId != param1 || param2 == 3)
{
_requestCallback = param3;
_requestMode = param2;
_requestAnimId = param1;
_bReload = true;
_bounceOverride = param1 != 17;
}
}
public function preload(param1:Array, param2:Function) : void
{
var _loc4_:int = 0;
_preloadCallback = param2;
var _loc3_:Array = [];
while(_loc4_ < param1.length)
{
buildRequestArray(param1[_loc4_],_loc3_,null);
_loc4_++;
}
_preloadRequestedIds.addAll(_loc3_);
requestImages(_loc3_);
}
private function heartbeat() : Boolean
{
var _loc1_:Boolean = false;
if(_bReload)
{
loadAnim();
}
if(_totalFrames == 0)
{
return false;
}
if(_mode == 3 && _callback != null)
{
_callback(_totalFrames);
_callback = null;
}
if(_frame >= _totalFrames)
{
if(_mode == 1)
{
_frame = _totalFrames > 0 ? _totalFrames - 1 : 0;
}
else
{
_frame = 0;
}
if(_callback != null)
{
_callback(this,_animId);
_callback = null;
}
}
if(_avatarEnabled)
{
_lastAnchorPoint.copyFrom(_bitmap.anchorPoint);
_loc1_ = _bitmap.paint(_frame,_hFlip);
if(!_lastAnchorPoint.equals(_bitmap.anchorPoint))
{
_bReposition = true;
}
}
calcBounceOffset();
if(_bReposition)
{
updateBitmapPos();
}
if(!_bPause && _mode != 3)
{
_frame = _frame + 1;
}
return _loc1_;
}
private function calcBounceOffset() : void
{
var _loc3_:int = 0;
var _loc1_:int = 0;
var _loc2_:Number = NaN;
if(_bounceEnabled && !_bounceOverride)
{
_loc3_ = _bounceOffSet;
_loc1_ = 75;
_loc2_ = (_frame + 1) / _totalFrames;
_bounceOffSet = (1 - (2 * _loc2_ - 1) * (2 * _loc2_ - 1)) * _loc1_;
if(_bounceOffSet != _loc3_)
{
if(_local && _frame == 0)
{
SBAudio.playCachedSound("BOUNCE");
}
_bReposition = true;
}
}
else if(_bounceOffSet != 0)
{
_bounceOffSet = 0;
_bReposition = true;
}
}
private function updateBitmapPos() : void
{
var _loc3_:Matrix = null;
var _loc4_:Point = _bitmap.anchorPoint;
var _loc1_:int = _x + _loc4_.x + _xOff;
var _loc2_:int = _y + _loc4_.y + _yOff - _bounceOffSet;
if(_rotation)
{
_loc3_ = _bitmap.transform.matrix;
_loc3_.identity();
_loc3_.translate(_loc4_.x + _xOff,_loc4_.y + _yOff);
_loc3_.rotate(_rotation * (3.141592653589793 / 180));
_loc3_.translate(_loc1_,_loc2_);
_bitmap.transform.matrix = _loc3_;
}
else
{
if(_bitmap.rotation != _rotation)
{
_bitmap.rotation = _rotation;
}
_bitmap.x = _loc1_;
_bitmap.y = _loc2_;
}
_bReposition = false;
}
private function loadAnim() : void
{
var _loc1_:int = 0;
if(_layers != null && _layers.length > 0)
{
_loc1_ = _requestAnimId != -1 ? _requestAnimId : _animId;
if(_loc1_ >= 0)
{
_requestAnimId = _loc1_;
requestAnim(_loc1_);
}
}
}
private function requestAnim(param1:int) : void
{
_bReload = false;
var _loc4_:Array = [];
var _loc2_:Array = [];
_order = {};
buildRequestArray(param1,_loc2_,_loc4_);
_loc2_.sort();
var _loc3_:String = _loc2_.join();
_colors = _loc4_;
_requestedCacheKey = _loc3_;
_receivedData = [];
_requestedIds = new Set();
_requestedIds.addAll(_loc2_);
requestImages(_loc2_);
}
private function buildRequestArray(param1:int, param2:Array, param3:Array) : void
{
var _loc6_:int = 0;
var _loc4_:uint = ImageArrayHelper.packId(_avDefId,param1,0);
if(_hasSequence(_loc4_))
{
param2.push(_loc4_);
}
for each(var _loc5_:Object in _layers)
{
_loc4_ = ImageArrayHelper.packId(_avDefId,param1,_loc5_.l);
param2.push(_loc4_);
if(param3)
{
param3[_loc4_] = _loc5_.c;
if(_order)
{
_order[_loc4_] = _loc6_;
}
}
_loc6_++;
}
}
private function requestImages(param1:Array) : void
{
ImageServerURL.instance.addEventListener("OnNewData",onReceiveData,false,0,true);
for each(var _loc2_:uint in param1)
{
ImageServerURL.instance.requestImage(_loc2_);
}
}
private function onReceiveData(param1:ImageServerEvent) : void
{
var _loc2_:* = 0;
var _loc3_:int = 0;
if(_preloadRequestedIds.remove(param1.id))
{
if(_preloadRequestedIds.isEmpty())
{
if(_requestedIds.isEmpty())
{
ImageServerURL.instance.removeEventListener("OnNewData",onReceiveData);
}
if(_preloadCallback != null)
{
_preloadCallback(this);
}
}
}
if(_requestedIds.remove(param1.id))
{
_loc3_ = param1.layer;
if(_loc3_ > 0)
{
_loc2_ = uint(_colors[param1.id]);
}
if(param1.success)
{
_receivedData.push({
"l":_loc3_,
"d":param1.imageData,
"c":_loc2_,
"p":(_order && _order.hasOwnProperty(param1.id) ? int(_order[param1.id]) : -1)
});
}
if(_requestedIds.isEmpty())
{
if(_preloadRequestedIds.isEmpty())
{
ImageServerURL.instance.removeEventListener("OnNewData",onReceiveData);
}
// the first item in a slot keeps the slot's own place; more in
// the same slot get places of their own after it
// (LayerBitmap.slotFor), in the order they are listed
_receivedData.sortOn("p",16);
var _loc6_:Object = {};
for each(var _loc4_:Object in _receivedData)
{
var _loc7_:int = int(_loc6_[_loc4_.l]);
_loc6_[_loc4_.l] = _loc7_ + 1;
_bitmap.setLayer(LayerBitmap.slotFor(_loc4_.l,_loc7_),_loc4_.d,_loc4_.c,_requestedCacheKey);
}
finishAnimRequest();
_receivedData = null;
_requestedCacheKey = null;
_colors = null;
}
}
}
private function finishAnimRequest() : void
{
if(_mode != 2 && _mode != 3)
{
_frame = 0;
}
_mode = _requestMode;
if(_requestAnimId >= 0)
{
_animId = _requestAnimId;
}
_requestAnimId = -1;
_callback = _requestCallback;
_totalFrames = _bitmap.length;
}
}
}
class SingletonLock
{
public function SingletonLock()
{
super();
}
}
+826
View File
@@ -0,0 +1,826 @@
package com.sbi.graphics
{
import com.sbi.corelib.Set;
import com.sbi.loader.ImageServerURL;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
public class LayerBitmap extends Bitmap
{
public static const BACKGROUND_COLOR:uint = 0;
private var _anchorPoint:Point;
private var _activeLayerGroup:LayerGroup;
private var _bmin:Point;
private var _bmax:Point;
private var _lastFrame:int;
private var _lastHFlip:Boolean;
private var _blendColor:uint;
private var _cachedLayerGroups:Dictionary;
private var _currCacheKey:String;
public function LayerBitmap()
{
super();
_activeLayerGroup = new LayerGroup();
_anchorPoint = new Point();
_bmin = new Point();
_bmax = new Point();
_cachedLayerGroups = new Dictionary();
}
public function destroy() : void
{
if(_currCacheKey == null)
{
_activeLayerGroup.destroy();
}
for each(var _loc1_:LayerGroup in _cachedLayerGroups)
{
_loc1_.destroy();
}
_cachedLayerGroups = null;
if(this.bitmapData)
{
this.bitmapData.dispose();
this.bitmapData = null;
}
}
public function get length() : int
{
return _activeLayerGroup.length;
}
public function release() : void
{
for each(var _loc1_:LayerGroup in _cachedLayerGroups)
{
_loc1_.destroy();
}
_cachedLayerGroups = new Dictionary();
if(_currCacheKey == null)
{
_activeLayerGroup.destroy();
}
else
{
_currCacheKey = null;
}
_activeLayerGroup = new LayerGroup();
invalidate();
_lastHFlip = false;
}
public function invalidate() : void
{
_lastFrame = -1;
}
public function trimLayerGroups() : Set
{
var _loc3_:LayerGroup = null;
var _loc2_:Set = new Set();
for(var _loc4_:Object in _cachedLayerGroups)
{
if(_loc4_ != _currCacheKey)
{
_loc3_ = _cachedLayerGroups[_loc4_];
if(_loc3_.decrementTtl() < 1)
{
delete _cachedLayerGroups[_loc4_];
_loc3_.destroy();
continue;
}
}
for each(var _loc1_:int in String(_loc4_).split(","))
{
_loc2_.add(_loc1_);
}
}
return _loc2_;
}
// where an item goes: the first in a body slot (1 to 10) has the slot's
// own place, as the game always had it; a second, third ... worn in the
// same slot goes to 100 + slot * 16 + n, which paint draws right after
// that slot, so that every worn item shows, the later over the earlier
public static function slotFor(param1:int, param2:int) : int
{
if(param2 <= 0 || param1 <= 0)
{
return param1;
}
return 100 + param1 * 16 + Math.min(param2,15);
}
public function setLayer(param1:int, param2:Object, param3:uint, param4:String = null) : void
{
if(param1 < 0 || param1 > 10 && param1 < 117 || param1 > 275)
{
return;
}
if(param4 != null)
{
if(param4 != _currCacheKey)
{
if(_currCacheKey == null)
{
_cachedLayerGroups[param4] = _activeLayerGroup;
}
else
{
if(!_cachedLayerGroups[param4])
{
_cachedLayerGroups[param4] = new LayerGroup();
}
_activeLayerGroup = _cachedLayerGroups[param4];
}
_currCacheKey = param4;
}
}
if(param2)
{
if(_activeLayerGroup.layers[param1] == null)
{
_activeLayerGroup.layers[param1] = {
"c":param3,
"lastColor":-1,
"blendColor":-1
};
_activeLayerGroup.checkColors = true;
}
else
{
setLayerColor(param1,param3);
}
_activeLayerGroup.layers[param1].o = param2;
}
else
{
delete _activeLayerGroup.layers[param1];
_activeLayerGroup.checkColors = true;
}
invalidate();
}
public function setLayerColor(param1:int, param2:uint) : void
{
var _loc3_:Object = _activeLayerGroup.layers[param1];
if(_loc3_ && param2 != _loc3_.c)
{
_loc3_.c = param2;
_activeLayerGroup.checkColors = true;
}
}
public function setBlendColor(param1:uint) : void
{
if(_blendColor != param1)
{
_blendColor = param1;
for each(var _loc2_:LayerGroup in _cachedLayerGroups)
{
_loc2_.checkColors = true;
}
}
}
public function switchLayerGroup(param1:Array, param2:String = null) : Boolean
{
var _loc6_:int = 0;
var _loc4_:LayerGroup = param2 == null ? _activeLayerGroup : _cachedLayerGroups[param2];
if(_loc4_ == null || param1 == null)
{
return false;
}
var _loc3_:ImageServerURL = ImageServerURL.instance;
for each(var _loc5_:Object in param1)
{
_loc6_ = _loc3_.getLayerIndex(_loc5_.l);
if(!_loc4_.layers[_loc6_])
{
return false;
}
if(_loc4_.layers[_loc6_].c != _loc5_.c)
{
_loc4_.layers[_loc6_].c = _loc5_.c;
_loc4_.checkColors = true;
}
}
if(param2 != null && param2 != _currCacheKey)
{
_activeLayerGroup = _cachedLayerGroups[param2];
_currCacheKey = param2;
}
invalidate();
return true;
}
public function get anchorPoint() : Point
{
return _anchorPoint;
}
private function refreshLayerPalette(param1:int) : Boolean
{
var _loc7_:Boolean = false;
var _loc5_:* = 0;
var _loc6_:Array = null;
var _loc8_:int = 0;
var _loc10_:int = 0;
var _loc2_:int = 0;
var _loc3_:int = 0;
var _loc4_:int = 0;
var _loc9_:Object = _activeLayerGroup.layers[param1];
if(_loc9_)
{
_loc7_ = param1 == 3;
if(_loc9_.lastColor != _loc9_.c || !_loc7_ && _loc9_.blendColor != _blendColor)
{
_loc5_ = uint(_loc9_.c);
_loc6_ = PaletteHelper.gamePalette;
_loc8_ = _loc5_ >> 24 & 0xFF;
_loc10_ = _loc5_ >> 16 & 0xFF;
_loc2_ = _loc5_ >> 8 & 0xFF;
_loc3_ = _loc5_ & 0xFF;
if(!_loc9_.pal)
{
_loc9_.pal = [];
}
PaletteHelper.BuildAnimalPalette(_loc9_.pal,_loc6_[_loc8_],_loc6_[_loc10_],_loc6_[_loc2_],_loc6_[_loc3_]);
if(!_loc7_)
{
_loc4_ = _blendColor >> 24 & 0xFF;
if(_loc4_ > 0)
{
PaletteHelper.adjustPaletteColor(_loc9_.pal,_blendColor);
}
_loc9_.blendColor = _blendColor;
}
_loc9_.lastColor = _loc5_;
return true;
}
}
return false;
}
private function refreshAllPalettes() : Boolean
{
var _loc2_:Boolean = false;
for(var _loc1_ in _activeLayerGroup.layers)
{
if(_loc1_ > 0)
{
if(refreshLayerPalette(_loc1_))
{
_loc2_ = true;
}
}
}
if(_loc2_)
{
_activeLayerGroup.invalidate();
}
return _loc2_;
}
private function calcBounds(param1:int) : void
{
var _loc4_:Object = null;
var _loc10_:Object = null;
var _loc3_:int = 0;
var _loc8_:Object = null;
var _loc2_:int = 0;
var _loc9_:int = 0;
var _loc5_:int = 0;
var _loc6_:int = 0;
_bmin.setTo(1000,1000);
_bmax.setTo(0,0);
for(var _loc7_ in _activeLayerGroup.layers)
{
if(_loc7_ != 0)
{
_loc4_ = _activeLayerGroup.layers[_loc7_];
_loc10_ = _loc4_.o;
if(_loc10_.v != 117967104)
{
return;
}
_loc3_ = int(_loc10_.f.length);
if(param1 < _loc3_)
{
_loc8_ = _loc10_.f[param1];
if(_loc8_)
{
_loc2_ = int(_loc8_.x);
_loc9_ = int(_loc8_.y);
_loc5_ = int(_loc8_.w);
_loc6_ = int(_loc8_.h);
if(_loc2_ < _bmin.x)
{
_bmin.x = _loc2_;
}
if(_loc9_ < _bmin.y)
{
_bmin.y = _loc9_;
}
if(_loc2_ + _loc5_ > _bmax.x)
{
_bmax.x = _loc2_ + _loc5_;
}
if(_loc9_ + _loc6_ > _bmax.y)
{
_bmax.y = _loc9_ + _loc6_;
}
}
}
}
}
if(_bmin.x == 1000 || _bmin.y == 1000)
{
trace("WARNING: detected frame with unexpected bounds - currCacheKey:" + _currCacheKey + " index:" + param1 + " bmin.x:" + _bmin.x + " bmin.y:" + _bmin.y + " bmax.x:" + _bmax.x + " bmax.y:" + _bmax.y);
_bmin.copyFrom(_bmax);
}
}
private function switchFrame() : Boolean
{
var _loc1_:Boolean = false;
var _loc2_:Array = _activeLayerGroup.paintedFrames;
if(!_loc2_[_lastFrame])
{
_loc2_[_lastFrame] = [];
createFrame(_loc2_[_lastFrame]);
}
else if(_loc2_[_lastFrame][_lastHFlip] != null && _loc2_[_lastFrame][_lastHFlip].isValid)
{
_loc2_[_lastFrame][_lastHFlip].copyBoundsTo(_bmin,_bmax);
_loc1_ = true;
}
else if(_loc2_[_lastFrame][!_lastHFlip] != null && _loc2_[_lastFrame][!_lastHFlip].isValid)
{
_loc2_[_lastFrame][_lastHFlip] = _loc2_[_lastFrame][!_lastHFlip].flip();
_loc2_[_lastFrame][_lastHFlip].copyBoundsTo(_bmin,_bmax);
_loc1_ = true;
}
else
{
createFrame(_loc2_[_lastFrame]);
}
this.bitmapData = _loc2_[_lastFrame][_lastHFlip].frameData;
_loc2_[_lastFrame][_lastHFlip].updateAnchorPoint(_anchorPoint,_lastHFlip);
return _loc1_;
}
private function createFrame(param1:Array) : void
{
calcBounds(_lastFrame);
if(param1[_lastHFlip] == null)
{
param1[_lastHFlip] = new PaintedFrame(_bmin,_bmax);
}
else if(!param1[_lastHFlip].validateBounds(_bmin,_bmax))
{
param1[_lastHFlip].destroy();
param1[_lastHFlip] = new PaintedFrame(_bmin,_bmax);
}
else
{
param1[_lastHFlip].isValid = true;
}
}
public function paint(param1:int, param2:Boolean = false, param3:Boolean = true) : Boolean
{
var _loc6_:Object = null;
var _loc4_:Boolean = false;
var _loc7_:Boolean = false;
var _loc5_:int = 0;
_activeLayerGroup.resetTtl();
if(param3 && _activeLayerGroup.layers[0] != null)
{
_loc6_ = _activeLayerGroup.layers[0];
param1 = int(_loc6_.o.f[param1]);
}
if(_activeLayerGroup.checkColors)
{
_loc7_ = refreshAllPalettes();
_activeLayerGroup.checkColors = false;
}
if(param1 != _lastFrame || param2 != _lastHFlip || _loc7_)
{
_lastFrame = param1;
_lastHFlip = param2;
if(!switchFrame())
{
_loc5_ = 1;
while(_loc5_ <= 10)
{
_loc6_ = _activeLayerGroup.layers[_loc5_];
if(_loc6_ != null && _loc6_.o != null && _loc6_.pal != null)
{
if(paintFrame(_loc6_.o,param1,_loc6_.pal,param2))
{
_loc4_ = true;
}
}
// more items worn in this slot (slotFor)
var _loc8_:int = 1;
while(_loc8_ <= 15)
{
_loc6_ = _activeLayerGroup.layers[100 + _loc5_ * 16 + _loc8_];
if(_loc6_ != null && _loc6_.o != null && _loc6_.pal != null)
{
if(paintFrame(_loc6_.o,param1,_loc6_.pal,param2))
{
_loc4_ = true;
}
}
_loc8_++;
}
_loc5_++;
}
}
}
return _loc4_;
}
private function paintFrame(param1:Object, param2:int, param3:Array, param4:Boolean) : Boolean
{
var _loc25_:int = 0;
var _loc18_:int = 0;
var _loc13_:* = 0;
var _loc15_:* = 0;
var _loc31_:int = 0;
var _loc20_:int = 0;
var _loc8_:int = 0;
var _loc26_:int = 0;
var _loc5_:int = 0;
var _loc21_:int = 0;
var _loc10_:int = 0;
var _loc27_:int = 0;
var _loc9_:int = 0;
var _loc14_:Number = NaN;
var _loc23_:* = 0;
var _loc12_:int = 0;
if(param1 == null || !param1.hasOwnProperty("f"))
{
return false;
}
if(param2 >= param1.f.length)
{
return false;
}
var _loc24_:Object = param1.f[param2];
if(!_loc24_)
{
return false;
}
var _loc6_:BitmapData = this.bitmapData;
if(_loc6_ == null)
{
return false;
}
_loc6_.lock();
var _loc22_:ByteArray = _loc24_.b;
var _loc11_:int = int(_loc24_.x);
var _loc7_:int = int(_loc24_.y);
var _loc28_:int = int(_loc24_.w);
var _loc17_:int = int(_loc24_.h);
_loc11_ -= _bmin.x;
_loc7_ -= _bmin.y;
_loc28_ += _loc11_;
_loc22_.position = 0;
var _loc16_:int = int(_loc22_.length);
var _loc29_:int = _loc11_;
var _loc30_:int = _loc7_;
var _loc19_:int = _loc28_ - _loc11_;
if(!param4)
{
while(_loc22_.position < _loc16_)
{
_loc25_ = int(_loc22_.readUnsignedByte());
_loc18_ = 1;
if((_loc25_ & 0x80) == 128)
{
_loc25_ &= 127;
_loc18_ = _loc22_.readUnsignedByte() + 1;
}
if(_loc25_ == 0)
{
_loc29_ += _loc18_;
if(_loc29_ >= _loc28_)
{
_loc18_ = _loc29_ - _loc28_;
_loc29_ = _loc11_ + _loc18_ % _loc19_;
_loc30_ += _loc18_ / _loc19_ + 1;
}
}
else
{
_loc13_ = uint(param3[_loc25_]);
if(_loc13_ >= 4278190080)
{
if(_loc29_ + _loc18_ < _loc28_)
{
while(--_loc18_ > -1)
{
_loc6_.setPixel32(_loc29_++,_loc30_,_loc13_);
}
}
else
{
while(--_loc18_ > -1)
{
_loc6_.setPixel32(_loc29_++,_loc30_,_loc13_);
if(_loc29_ == _loc28_)
{
_loc29_ = _loc11_;
_loc30_++;
}
}
}
}
else
{
while(--_loc18_ > -1)
{
_loc15_ = _loc6_.getPixel32(_loc29_,_loc30_);
if(_loc15_ != 0)
{
_loc26_ = _loc13_ >> 24 & 0xFF;
_loc31_ = _loc13_ >> 16 & 0xFF;
_loc20_ = _loc13_ >> 8 & 0xFF;
_loc8_ = _loc13_ & 0xFF;
_loc27_ = _loc15_ >> 24 & 0xFF;
_loc5_ = _loc15_ >> 16 & 0xFF;
_loc21_ = _loc15_ >> 8 & 0xFF;
_loc10_ = _loc15_ & 0xFF;
if(_loc26_ == 192)
{
_loc31_ = (_loc31_ + _loc31_ + _loc31_ + _loc5_) * 0.25;
_loc20_ = (_loc20_ + _loc20_ + _loc20_ + _loc21_) * 0.25;
_loc8_ = (_loc8_ + _loc8_ + _loc8_ + _loc10_) * 0.25;
}
else if(_loc26_ == 128)
{
_loc31_ = (_loc31_ + _loc5_) * 0.5;
_loc20_ = (_loc20_ + _loc21_) * 0.5;
_loc8_ = (_loc8_ + _loc10_) * 0.5;
}
else
{
_loc31_ = (_loc31_ + _loc5_ + _loc5_ + _loc5_) * 0.25;
_loc20_ = (_loc20_ + _loc21_ + _loc21_ + _loc21_) * 0.25;
_loc8_ = (_loc8_ + _loc10_ + _loc10_ + _loc10_) * 0.25;
}
if(_loc27_ > _loc26_)
{
_loc26_ = _loc27_;
}
_loc13_ = uint(_loc26_ << 24 | _loc31_ << 16 | _loc20_ << 8 | _loc8_);
}
_loc6_.setPixel32(_loc29_++,_loc30_,_loc13_);
if(_loc29_ == _loc28_)
{
_loc29_ = _loc11_;
_loc30_++;
}
}
}
}
}
}
else
{
_loc9_ = _bmax.x - _bmin.x;
while(_loc22_.position < _loc16_)
{
_loc25_ = int(_loc22_.readUnsignedByte());
_loc18_ = 1;
if((_loc25_ & 0x80) == 128)
{
_loc25_ &= 127;
_loc18_ = _loc22_.readUnsignedByte() + 1;
}
if(_loc25_ == 0)
{
_loc29_ += _loc18_;
if(_loc29_ >= _loc28_)
{
_loc18_ = _loc29_ - _loc28_;
_loc29_ = _loc11_ + _loc18_ % _loc19_;
_loc30_ += _loc18_ / _loc19_ + 1;
}
}
else
{
_loc13_ = uint(param3[_loc25_]);
if(_loc13_ >= 4278190080)
{
if(_loc29_ + _loc18_ < _loc28_)
{
while(--_loc18_ > -1)
{
_loc6_.setPixel32(_loc9_ - _loc29_++,_loc30_,_loc13_);
}
}
else
{
while(--_loc18_ > -1)
{
_loc6_.setPixel32(_loc9_ - _loc29_++,_loc30_,_loc13_);
if(_loc29_ == _loc28_)
{
_loc29_ = _loc11_;
_loc30_++;
}
}
}
}
else
{
while(--_loc18_ > -1)
{
_loc15_ = _loc6_.getPixel32(_loc9_ - _loc29_,_loc30_);
if(_loc15_ != 0)
{
_loc26_ = _loc13_ >> 24 & 0xFF;
_loc31_ = _loc13_ >> 16 & 0xFF;
_loc20_ = _loc13_ >> 8 & 0xFF;
_loc8_ = _loc13_ & 0xFF;
_loc27_ = _loc15_ >> 24 & 0xFF;
_loc5_ = _loc15_ >> 16 & 0xFF;
_loc21_ = _loc15_ >> 8 & 0xFF;
_loc10_ = _loc15_ & 0xFF;
switch(_loc26_)
{
case 192:
_loc31_ = (_loc31_ + _loc31_ + _loc31_ + _loc5_) * 0.25;
_loc20_ = (_loc20_ + _loc20_ + _loc20_ + _loc21_) * 0.25;
_loc8_ = (_loc8_ + _loc8_ + _loc8_ + _loc10_) * 0.25;
break;
case 128:
_loc31_ = (_loc31_ + _loc5_) * 0.5;
_loc20_ = (_loc20_ + _loc21_) * 0.5;
_loc8_ = (_loc8_ + _loc10_) * 0.5;
break;
case 64:
_loc31_ = (_loc31_ + _loc5_ + _loc5_ + _loc5_) * 0.25;
_loc20_ = (_loc20_ + _loc21_ + _loc21_ + _loc21_) * 0.25;
_loc8_ = (_loc8_ + _loc10_ + _loc10_ + _loc10_) * 0.25;
}
if(_loc27_ > _loc26_)
{
_loc26_ = _loc27_;
}
_loc13_ = uint(_loc26_ << 24 | _loc31_ << 16 | _loc20_ << 8 | _loc8_);
}
_loc6_.setPixel32(_loc9_ - _loc29_++,_loc30_,_loc13_);
if(_loc29_ == _loc28_)
{
_loc29_ = _loc11_;
_loc30_++;
}
}
}
}
}
}
if(_loc24_.hasOwnProperty("s"))
{
_loc12_ = int(_loc24_.sm);
_loc22_ = _loc24_.s;
_loc16_ = int(_loc22_.length);
_loc22_.position = 0;
_loc29_ = _loc11_;
_loc30_ = _loc7_;
if(!param4)
{
while(_loc22_.position < _loc16_)
{
_loc25_ = int(_loc22_.readUnsignedByte());
_loc18_ = 1;
if((_loc25_ & 0x80) == 128)
{
_loc25_ &= 127;
_loc18_ = _loc22_.readUnsignedByte() + 1;
}
if(_loc25_ == 0)
{
_loc29_ += _loc18_;
if(_loc29_ >= _loc28_)
{
_loc18_ = _loc29_ - _loc28_;
_loc29_ = _loc11_ + _loc18_ % _loc19_;
_loc30_ += _loc18_ / _loc19_ + 1;
}
}
else
{
_loc13_ = uint(_loc25_ << _loc12_);
_loc13_ = uint(_loc13_ + 24);
if(_loc13_ > 255)
{
_loc14_ = 1;
}
else
{
_loc14_ = _loc13_ / 255;
}
while(--_loc18_ > -1)
{
_loc15_ = _loc6_.getPixel32(_loc29_,_loc30_);
if(_loc15_ != 0)
{
_loc26_ = _loc15_ >> 24 & 0xFF;
_loc31_ = (_loc15_ >> 16 & 0xFF) * _loc14_;
_loc20_ = (_loc15_ >> 8 & 0xFF) * _loc14_;
_loc8_ = (_loc15_ & 0xFF) * _loc14_;
_loc23_ = uint(_loc26_ << 24 | _loc31_ << 16 | _loc20_ << 8 | _loc8_);
_loc6_.setPixel32(_loc29_,_loc30_,_loc23_);
}
if(++_loc29_ == _loc28_)
{
_loc29_ = _loc11_;
_loc30_++;
}
}
}
}
}
else
{
_loc9_ = _bmax.x - _bmin.x;
while(_loc22_.position < _loc16_)
{
_loc25_ = int(_loc22_.readUnsignedByte());
_loc18_ = 1;
if((_loc25_ & 0x80) == 128)
{
_loc25_ &= 127;
_loc18_ = _loc22_.readUnsignedByte() + 1;
}
if(_loc25_ == 0)
{
_loc29_ += _loc18_;
if(_loc29_ >= _loc28_)
{
_loc18_ = _loc29_ - _loc28_;
_loc29_ = _loc11_ + _loc18_ % _loc19_;
_loc30_ += _loc18_ / _loc19_ + 1;
}
}
else
{
_loc13_ = uint(_loc25_ << _loc12_);
_loc13_ = uint(_loc13_ + 24);
if(_loc13_ > 255)
{
_loc14_ = 1;
}
else
{
_loc14_ = _loc13_ / 255;
}
while(--_loc18_ > -1)
{
_loc15_ = _loc6_.getPixel32(_loc9_ - _loc29_,_loc30_);
if(_loc15_ != 0)
{
_loc26_ = _loc15_ >> 24 & 0xFF;
_loc31_ = (_loc15_ >> 16 & 0xFF) * _loc14_;
_loc20_ = (_loc15_ >> 8 & 0xFF) * _loc14_;
_loc8_ = (_loc15_ & 0xFF) * _loc14_;
_loc23_ = uint(_loc26_ << 24 | _loc31_ << 16 | _loc20_ << 8 | _loc8_);
_loc6_.setPixel32(_loc9_ - _loc29_,_loc30_,_loc23_);
}
if(++_loc29_ == _loc28_)
{
_loc29_ = _loc11_;
_loc30_++;
}
}
}
}
}
}
_loc6_.unlock();
return true;
}
}
}
+9 -4
View File
@@ -17,6 +17,11 @@ package loader
public class MediaHelper
{
// a report to the server at each step of every media load: it was for
// finding a Wine decoding fault, and at 300 players it was most of the
// web traffic. failures are still reported.
private static const TRACE_LOADS:Boolean = false;
private var _id:uint;
private var _callback:Function;
@@ -51,7 +56,7 @@ package loader
_loader = new Loader();
MediaFileServer.instance.addEventListener("OnNewData",handleMediaData);
MediaFileServer.instance.addEventListener("progress",onLoadProgress);
GlobalErrorCatch.reportToServer("media " + _id + " requested");
if(TRACE_LOADS) GlobalErrorCatch.reportToServer("media " + _id + " requested");
MediaFileServer.instance.requestFile(_id);
}
@@ -81,7 +86,7 @@ package loader
{
return;
}
GlobalErrorCatch.reportToServer("media " + _id + " data success=" + param1.success + " length=" + (param1.data ? param1.data.length : -1));
if(TRACE_LOADS) GlobalErrorCatch.reportToServer("media " + _id + " data success=" + param1.success + " length=" + (param1.data ? param1.data.length : -1));
if(param1.success)
{
MediaFileServer.instance.removeEventListener("OnNewData",handleMediaData);
@@ -188,7 +193,7 @@ package loader
param1.target.removeEventListener("complete",onBytesLoaded);
param1.target.removeEventListener("OnLoadProgress",onLoadProgress);
_loadProgressFunc = null;
GlobalErrorCatch.reportToServer("media " + _id + " decoded, waitingForSharedLibrary=" + Boolean(_mc.hasOwnProperty("__rslPreloader") && _mc.__rslPreloader));
if(TRACE_LOADS) GlobalErrorCatch.reportToServer("media " + _id + " decoded, waitingForSharedLibrary=" + Boolean(_mc.hasOwnProperty("__rslPreloader") && _mc.__rslPreloader));
if(_mc.hasOwnProperty("__rslPreloader") && _mc.__rslPreloader)
{
_mc.addEventListener("enterFrame",onFrame);
@@ -204,7 +209,7 @@ package loader
{
if(_mc.__rslPreloader == null)
{
GlobalErrorCatch.reportToServer("media " + _id + " shared library ready");
if(TRACE_LOADS) GlobalErrorCatch.reportToServer("media " + _id + " shared library ready");
_mc.removeEventListener("enterFrame",onFrame);
if(_callback != null)
{
+5 -1
View File
@@ -159,7 +159,7 @@ package gui
"type":TOGGLE_TYPE_JOIN,
"frame":"itemFinder",
"iconFrame":"redeemCode",
"labelLabel":"Item Finder",
"labelLabel":"Item Giver",
"btnLabel":"Open"
},{
"type":TOGGLE_TYPE_JOIN,
@@ -218,11 +218,15 @@ package gui
"frame":"redeemCode",
"labelTxt":24819,
"btnTxt":24820
/* the game's "World" row (choose a server) is out: there is one
world, this server does not answer the list it asks for (rm),
and the picker then waited behind its spinner for ever.
},{
"type":TOGGLE_TYPE_JOIN,
"frame":"world",
"labelTxt":6395,
"btnTxt":6366
*/
},{
"type":TOGGLE_TYPE_TOGGLE_BTN,
"frame":"nameBadge",
File diff suppressed because it is too large. Load diff
+997
View File
@@ -0,0 +1,997 @@
package Party
{
import avatar.AvatarManager;
import avatar.UserInfo;
import com.greensock.TimelineLite;
import com.greensock.TweenLite;
import com.greensock.easing.Expo;
import com.sbi.popup.SBOkPopup;
import customParty.CustomPartyCreatePopup;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.getTimer;
import game.MinigameManager;
import game.MinigameXtCommManager;
import gui.DarkenManager;
import gui.GuiManager;
import gui.LoadingSpiral;
import gui.WindowAndScrollbarGenerator;
import gui.itemWindows.ItemWindowParty;
import loader.MediaHelper;
import localization.LocalizationManager;
import quest.QuestXtCommManager;
import room.RoomManagerWorld;
import room.RoomXtCommManager;
public class PartyPopup
{
protected const PARTY_POPUP_MEDIA_ID:int = 1215;
protected const REQUEST_INTERVAL:Number = 10000;
protected const ADDITIONAL_ADVENTURE_SCRIPT_ID:int = 283;
protected var _mediaHelper:MediaHelper;
protected var _partyPopup:MovieClip;
protected var _closeCallback:Function;
protected var _customPartiesLoadingSpiral:LoadingSpiral;
protected var _ajPartiesLoadingSpiral:LoadingSpiral;
protected var _ajPartySingleLoadingSpiral:LoadingSpiral;
protected var _headersLoadingSpiral:LoadingSpiral;
protected var _partyDefIds:Array;
protected var _secToStart:Array;
protected var _additionalScriptDefs:Array;
protected var _additionalHeaderData:Array;
protected var _partyMediaIds:Array;
protected var _secToEnd:Array;
protected var _partyDefs:Object;
protected var _mins:Array;
protected var _hours:Array;
protected var _customPartyData:Array;
protected var _adventureHeaderWindow:ItemWindowParty;
protected var _additionalHeaderWindow1:ItemWindowParty;
protected var _additionalHeaderWindow2:ItemWindowParty;
protected var _ajItemWindows:WindowAndScrollbarGenerator;
protected var _ajItemWindowSingle:ItemWindowParty;
protected var _customPartyItemWindows:WindowAndScrollbarGenerator;
protected var _adventureHeaderMediaId:int;
protected var _timeOffset:int;
protected var _initialTime:int;
protected var _numSecPassed:int;
protected var _hadReceivedPartyList:Boolean;
protected var _partiesListLoaded:Boolean;
protected var _useMinimalist:Boolean;
protected var _tabTimeLine:TimelineLite;
protected var _customPartyCreatePopup:CustomPartyCreatePopup;
public function PartyPopup(param1:Function, param2:int)
{
super();
DarkenManager.showLoadingSpiral(true);
_timeOffset = param2;
_closeCallback = param1;
_useMinimalist = Utility.daysSinceCreated() < 1;
_mediaHelper = new MediaHelper();
_mediaHelper.init(1215,onPartyPopupLoaded);
}
public function destroy(param1:Boolean = false) : void
{
_closeCallback = null;
_hadReceivedPartyList = false;
if(_mediaHelper)
{
_mediaHelper.destroy();
_mediaHelper = null;
}
if(_adventureHeaderWindow)
{
_adventureHeaderWindow.destroy();
_adventureHeaderWindow = null;
}
if(_additionalHeaderWindow1)
{
_additionalHeaderWindow1.destroy();
_additionalHeaderWindow1 = null;
}
if(_additionalHeaderWindow2)
{
_additionalHeaderWindow2.destroy();
_additionalHeaderWindow2 = null;
}
if(_ajItemWindowSingle)
{
_ajItemWindowSingle.destroy();
_ajItemWindowSingle = null;
}
if(_ajItemWindows)
{
_ajItemWindows.destroy();
_ajItemWindows = null;
}
if(_customPartiesLoadingSpiral)
{
_customPartiesLoadingSpiral.destroy();
_customPartiesLoadingSpiral = null;
}
if(_ajPartiesLoadingSpiral)
{
_ajPartiesLoadingSpiral.destroy();
_ajPartiesLoadingSpiral = null;
}
if(_ajPartySingleLoadingSpiral)
{
_ajPartySingleLoadingSpiral.destroy();
_ajPartySingleLoadingSpiral = null;
}
if(_headersLoadingSpiral)
{
_headersLoadingSpiral.destroy();
_headersLoadingSpiral = null;
}
if(_tabTimeLine)
{
_tabTimeLine.kill();
_tabTimeLine = null;
}
onCustomPartyCreateClose(param1);
DarkenManager.unDarken(_partyPopup.parent);
if(GuiManager.guiLayer.contains(_partyPopup.parent))
{
GuiManager.guiLayer.removeChild(_partyPopup.parent);
}
_partyPopup = null;
}
public function showPopup(param1:Boolean) : void
{
if(_partyPopup)
{
if(_customPartyCreatePopup)
{
_customPartyCreatePopup.showPopup(false);
}
_partyPopup.parent.visible = param1;
if(param1)
{
DarkenManager.darken(_partyPopup.parent);
}
else
{
DarkenManager.unDarken(_partyPopup.parent);
}
}
}
public function updateTime(param1:int) : void
{
if(_hadReceivedPartyList && param1 - _initialTime >= 10000)
{
_initialTime = param1;
onHeartbeat();
}
}
public function partyListResponse(param1:Object) : void
{
var _loc5_:int = 0;
var _loc6_:Array = null;
var _loc3_:int = 0;
var _loc8_:int = 0;
var _loc7_:int = 0;
var _loc2_:int = 0;
var _loc9_:Object = null;
var _loc4_:String = null;
if(_partyPopup)
{
_partyDefIds = [];
_secToStart = [];
_secToEnd = [];
_partyMediaIds = [];
_additionalHeaderData = [];
_loc6_ = [];
_loc3_ = int(param1[3]);
_loc8_ = 4;
if(_additionalScriptDefs == null)
{
GenericListXtCommManager.requestGenericList(283,OnAddionalAdventureScriptDefLoaded,param1);
return;
}
_adventureHeaderMediaId = 2253;
_loc2_ = -1;
if(_loc2_ != -1)
{
_additionalHeaderData.push({
"isParty":true,
"defId":_loc2_,
"mediaId":int(_partyDefs[_loc2_].mediaRefId),
"secToStart":0,
"secToEnd":0,
"headerTime":Utility.calculateTime(0)
});
}
if(_additionalScriptDefs.length > 0)
{
_loc7_ = 0;
while(_loc7_ < _additionalScriptDefs.length)
{
_loc9_ = QuestXtCommManager.getScriptDef(_additionalScriptDefs[_loc7_]);
if(_loc9_)
{
_additionalHeaderData.push({
"isParty":false,
"defId":_loc9_.defId,
"mediaId":_loc9_.bannerMediaRefId,
"secToStart":0,
"secToEnd":0,
"headerTime":Utility.calculateTime(0)
});
}
_loc7_++;
}
}
initializePartyPopup();
_loc4_ = _useMinimalist ? "Sml" : "";
switch(int(_additionalHeaderData.length))
{
case 0:
_partyPopup.gotoAndStop("header" + _loc4_);
break;
case 1:
_partyPopup.gotoAndStop("twoHeader" + _loc4_);
break;
default:
_partyPopup.gotoAndStop("threeHeader" + _loc4_);
}
setupCreateJoinButtonText();
addEventListeners();
setupLoadingSpirals();
buildHeaderPartyWindows();
_loc7_ = 0;
while(_loc7_ < _loc3_)
{
_partyDefIds[_loc7_] = int(param1[_loc8_]);
if(_partyDefs[int(param1[_loc8_])])
{
_loc5_ = int(_partyDefs[int(param1[_loc8_])].titleStrId);
if(!_loc6_[_loc5_])
{
_loc6_[_loc5_] = true;
}
_partyMediaIds[_loc7_] = int(_partyDefs[int(param1[_loc8_++])].mediaRefId);
_secToStart[_loc7_] = Number(param1[_loc8_++]);
if(_secToStart[_loc7_] != 0)
{
var _loc10_:int = _loc7_;
var _loc11_:Number = _secToStart[_loc10_] + _timeOffset;
_secToStart[_loc10_] = _loc11_;
}
_secToEnd[_loc7_] = Number(param1[_loc8_++]);
}
_loc7_++;
}
_loc6_ = null;
calculateTime();
_initialTime = getTimer();
buildAJSinglePartyWindow();
_hadReceivedPartyList = true;
if(!_useMinimalist)
{
PartyXtCommManager.sendCustomPartyListRequest(0,200);
}
}
}
public function customPartyListResponse(param1:Object) : void
{
var _loc2_:int = 0;
var _loc6_:int = 0;
var _loc10_:int = 0;
var _loc8_:int = 0;
var _loc7_:Object = null;
var _loc4_:Array = null;
_customPartyData = [];
var _loc9_:int = 2;
var _loc5_:Boolean = param1[_loc9_++] == "1";
var _loc3_:int = int(param1[_loc9_++]);
if(_loc3_ > 0)
{
_loc2_ = int(param1[_loc9_++]);
_loc6_ = int(param1[_loc9_++]);
_loc10_ = int(param1[_loc9_++]);
if(_loc10_ > 0)
{
_loc8_ = 0;
while(_loc8_ < _loc10_)
{
_loc7_ = {
"creator":param1[_loc9_++],
"name":param1[_loc9_++],
"nodeId":param1[_loc9_++],
"defId":int(param1[_loc9_++]),
"timeLeft":Number(param1[_loc9_++])
};
_loc4_ = _loc7_.name.split("|");
_loc7_.name = LocalizationManager.translateIdOnly(_loc4_[0]) + " " + LocalizationManager.translateIdOnly(_loc4_[1]) + " " + LocalizationManager.translateIdOnly(_loc4_[2]);
_customPartyData.push(_loc7_);
_loc8_++;
}
}
}
buildCustomPartyWindows();
}
private function onPartyPopupLoaded(param1:MovieClip) : void
{
_partyPopup = (param1.getChildAt(0) as MovieClip).partyFrames;
_mins = [];
_hours = [];
requestData();
}
protected function initializePartyPopup() : void
{
if(!GuiManager.guiLayer.contains(_partyPopup.parent))
{
DarkenManager.showLoadingSpiral(false);
_partyPopup.parent.x = 900 * 0.5;
_partyPopup.parent.y = 550 * 0.5;
GuiManager.guiLayer.addChild(_partyPopup.parent);
DarkenManager.darken(_partyPopup.parent);
}
}
protected function requestData() : void
{
if(PartyManager.partyDefs != null)
{
_partyDefs = PartyManager.partyDefs;
PartyXtCommManager.sendPartyListRequest();
}
else
{
PartyManager.requestPartyDefs(requestData);
}
}
protected function setupLoadingSpirals() : void
{
if(_partyPopup.itemWindowSpiral)
{
_headersLoadingSpiral = new LoadingSpiral(_partyPopup.itemWindowSpiral,_partyPopup.itemWindowSpiral.width * 0.5,_partyPopup.itemWindowSpiral.height * 0.5);
}
if(!_useMinimalist)
{
_customPartiesLoadingSpiral = new LoadingSpiral(_partyPopup.itemWindow,_partyPopup.itemWindow.width * 0.5,_partyPopup.itemWindow.height * 0.5);
_ajPartiesLoadingSpiral = new LoadingSpiral(_partyPopup.frameDrawerCont.itemWindow,_partyPopup.frameDrawerCont.itemWindow.width * 0.5,_partyPopup.frameDrawerCont.itemWindow.height * 0.5);
}
_ajPartySingleLoadingSpiral = new LoadingSpiral(_partyPopup.itemWindowAJ,_partyPopup.itemWindowAJ.width * 0.5,_partyPopup.itemWindowAJ.height * 0.5);
}
protected function buildAJSinglePartyWindow() : void
{
if(_ajItemWindowSingle)
{
_ajItemWindowSingle.destroy();
}
_ajItemWindowSingle = new ItemWindowParty(onSinglePartyWindowLoaded,_partyDefIds[0],"",0,ajWinMouseDown,null,null,null,{
"mediaRefId":_partyMediaIds,
"printTimeFunc":getAJWindowPrintTime
});
}
private function buildAJPartyWindows() : void
{
if(_ajItemWindows)
{
_ajItemWindows.destroy();
}
_ajItemWindows = new WindowAndScrollbarGenerator();
_ajItemWindows.init(_partyPopup.frameDrawerCont.itemWindow.width,_partyPopup.frameDrawerCont.itemWindow.height,3,0,1,6,0,0,2,0,1,ItemWindowParty,_partyDefIds,"",0,{"mouseDown":ajWinMouseDown},{
"mediaRefId":_partyMediaIds,
"printTimeFunc":getAJWindowPrintTime
},onAjPartiesLoaded,true,false,false);
}
private function buildCustomPartyWindows() : void
{
if(_customPartyItemWindows)
{
_customPartyItemWindows.destroy();
}
_customPartyItemWindows = new WindowAndScrollbarGenerator();
_customPartyItemWindows.init(_partyPopup.itemWindow.width,_partyPopup.itemWindow.height,4,0,1,4,0,0,2,0,1,ItemWindowParty,_customPartyData,"",0,{"mouseDown":customWinMouseDown},{"printTimeFunc":getCustomWindowPrintTime},onCustomPartiesLoaded,true,false,false);
}
protected function buildHeaderPartyWindows() : void
{
if(_adventureHeaderWindow)
{
_adventureHeaderWindow.destroy();
_adventureHeaderWindow = null;
}
_adventureHeaderWindow = new ItemWindowParty(onSinglePartyWindowLoaded,null,"",0,singleWinMouseDown,null,null,null,{"mediaRefId":[_adventureHeaderMediaId]});
if(_additionalHeaderData.length > 0)
{
if(_additionalHeaderWindow1)
{
_additionalHeaderWindow1.destroy();
_additionalHeaderWindow1 = null;
}
_additionalHeaderWindow1 = new ItemWindowParty(onSinglePartyWindowLoaded,null,"",0,singleWinMouseDown,null,null,null,{
"mediaRefId":[_additionalHeaderData[0].mediaId],
"additionalIndex":0
});
if(_additionalHeaderData.length == 2)
{
if(_additionalHeaderWindow2)
{
_additionalHeaderWindow2.destroy();
_additionalHeaderWindow2 = null;
}
_additionalHeaderWindow2 = new ItemWindowParty(onSinglePartyWindowLoaded,null,"",0,singleWinMouseDown,null,null,null,{
"mediaRefId":[_additionalHeaderData[1].mediaId],
"additionalIndex":1
});
}
}
}
private function calculatePrintTime(param1:int, param2:Boolean = false) : String
{
return Utility.calculatePrintTime(_mins[param1],_hours[param1],param2);
}
protected function calculateTime() : void
{
var _loc2_:Object = null;
var _loc1_:int = 0;
_loc1_ = 0;
while(_loc1_ < _secToStart.length)
{
_loc2_ = Utility.calculateTime(_secToStart[_loc1_]);
_mins[_loc1_] = _loc2_.mins;
_hours[_loc1_] = _loc2_.hours;
_loc1_++;
}
}
private function rebuildList() : void
{
var _loc1_:int = 0;
var _loc3_:int = 0;
var _loc2_:Array = [];
_partyMediaIds = [];
_loc3_ = 0;
while(_loc3_ < _partyDefIds.length)
{
_loc1_ = int(_partyDefs[_partyDefIds[_loc3_]].titleStrId);
if(!_loc2_[_loc1_])
{
_loc2_[_loc1_] = true;
}
_partyMediaIds[_loc3_] = int(_partyDefs[_partyDefIds[_loc3_]].mediaRefId);
_loc3_++;
}
if(!_useMinimalist)
{
buildAJPartyWindows();
}
}
private function getAJWindowPrintTime(param1:int) : String
{
return _secToStart[param1] > 0 ? calculatePrintTime(param1) : "";
}
private function getCustomWindowPrintTime(param1:int) : String
{
return Utility.calculatePrintTimeForCustomParties(param1);
}
protected function addEventListeners() : void
{
_partyPopup.addEventListener("mouseDown",onPopup,false,0,true);
_partyPopup.bx.addEventListener("mouseDown",onCloseBtn,false,0,true);
if(!_useMinimalist)
{
_partyPopup.frameDrawerCont.ajhqPartyTab_btn.addEventListener("mouseDown",onOpenPartyTab,false,0,true);
_partyPopup.frameDrawerCont.backTab_btn.addEventListener("mouseDown",onClosePartyTab,false,0,true);
_partyPopup.throwParty_btn.addEventListener("mouseDown",onThrowPartyBtn,false,0,true);
_partyPopup.goToParty_btn.addEventListener("mouseDown",onHostPartyBtn,false,0,true);
}
}
protected function removeEventListeners() : void
{
_partyPopup.removeEventListener("mouseDown",onPopup);
_partyPopup.bx.removeEventListener("mouseDown",onCloseBtn);
if(!_useMinimalist)
{
_partyPopup.frameDrawerCont.ajhqPartyTab_btn.removeEventListener("mouseDown",onOpenPartyTab);
_partyPopup.frameDrawerCont.backTab_btn.removeEventListener("mouseDown",onClosePartyTab);
_partyPopup.throwParty_btn.removeEventListener("mouseDown",onThrowPartyBtn);
_partyPopup.goToParty_btn.removeEventListener("mouseDown",onHostPartyBtn);
}
}
protected function setupCreateJoinButtonText() : void
{
var _loc1_:UserInfo = null;
var _loc2_:int = 0;
if(!_useMinimalist)
{
_loc1_ = gMainFrame.userInfo.playerUserInfo;
if(_loc1_)
{
if(_loc1_.isStillHosting)
{
_partyPopup.goToParty_btn.visible = true;
_partyPopup.throwParty_btn.visible = false;
}
else
{
_partyPopup.goToParty_btn.visible = false;
_partyPopup.throwParty_btn.visible = true;
}
}
}
}
protected function OnAddionalAdventureScriptDefLoaded(param1:int, param2:Array, param3:Object) : void
{
_additionalScriptDefs = param2;
partyListResponse(param3);
}
private function onSinglePartyWindowLoaded(param1:ItemWindowParty, param2:int = -1) : void
{
var _loc3_:Object = null;
if(param1 == _adventureHeaderWindow)
{
param1.setupTextAndAnims("");
_partyPopup.itemWindowHeader.addChild(param1);
}
else
{
if(param1 == _ajItemWindowSingle)
{
_ajPartySingleLoadingSpiral.visible = false;
(_ajItemWindowSingle.txt.timeTxt as TextField).gridFitType = "subpixel";
(_ajItemWindowSingle.txt.titleTxtCont.titleTxt as TextField).gridFitType = "subpixel";
_partyPopup.itemWindowAJ.addChild(param1);
return;
}
_loc3_ = param1 == _additionalHeaderWindow1 ? _additionalHeaderData[0] : _additionalHeaderData[1];
param1.defId = _loc3_.defId;
param1.setupTextAndAnims(_loc3_.secToStart > 0 ? Utility.calculatePrintTime(_loc3_.headerTime.mins,_loc3_.headerTime.hours) : "");
if(_loc3_.isParty)
{
param1.titleText = _partyDefs[_loc3_.defId].titleStrId;
}
if(param1 == _additionalHeaderWindow1)
{
_partyPopup.itemWindowHeader2.addChild(param1);
}
else if(param1 == _additionalHeaderWindow2)
{
_partyPopup.itemWindowHeader3.addChild(param1);
}
}
if(_additionalHeaderData.length == 2)
{
if(_additionalHeaderWindow2 && _additionalHeaderWindow2.parent != null && _additionalHeaderWindow1.parent != null && _adventureHeaderWindow.parent != null)
{
_headersLoadingSpiral.visible = false;
}
}
else if(_additionalHeaderWindow1 && _additionalHeaderWindow1.parent != null && _adventureHeaderWindow.parent != null)
{
_headersLoadingSpiral.visible = false;
}
}
private function onAjPartiesLoaded() : void
{
_ajPartiesLoadingSpiral.visible = false;
_partyPopup.frameDrawerCont.itemWindow.addChild(_ajItemWindows);
_partiesListLoaded = true;
}
private function onCustomPartiesLoaded() : void
{
// the party list closed before the hosted parties came (#1009)
if(_partyPopup == null || _customPartiesLoadingSpiral == null || _customPartyItemWindows == null)
{
return;
}
_customPartiesLoadingSpiral.visible = false;
_partyPopup.itemWindow.addChild(_customPartyItemWindows);
}
protected function onMinigameInfoResponse() : void
{
DarkenManager.showLoadingSpiral(false);
MinigameManager.handleGameClick({"typeDefId":102},null,true);
}
private function onHeartbeat() : void
{
var _loc4_:int = 0;
var _loc3_:int = 0;
var _loc1_:int = 0;
var _loc2_:ItemWindowParty = null;
var _loc6_:int = 0;
var _loc5_:int = 10;
_numSecPassed += _loc5_;
_loc4_ = 0;
while(_loc4_ < _secToStart.length)
{
_loc3_ = int(_hours[_loc4_]);
_loc1_ = int(_mins[_loc4_]);
if(_loc3_ > 0 || _loc1_ > 0)
{
var _loc7_:* = _loc4_;
var _loc8_:* = _secToStart[_loc7_] - _loc5_;
_secToStart[_loc7_] = _loc8_;
if(_secToStart[_loc4_] <= 0)
{
_loc3_ = 0;
_loc1_ = 0;
}
else if(_numSecPassed == 60)
{
if(_loc3_ > 0 && _loc1_ == 0)
{
_loc3_--;
}
if(_loc1_ == 0)
{
_loc1_ = 59;
}
else
{
_loc1_--;
}
}
_hours[_loc4_] = _loc3_;
_mins[_loc4_] = _loc1_;
if(_partiesListLoaded)
{
_loc2_ = ItemWindowParty(_ajItemWindows.mediaWindows[_loc4_]);
_loc2_.setupTextAndAnims(_loc3_ > 0 || _loc1_ > 0 ? calculatePrintTime(_loc4_) : "");
}
if(_loc4_ == 0)
{
_ajItemWindowSingle.setupTextAndAnims(_loc3_ > 0 || _loc1_ > 0 ? calculatePrintTime(_loc4_) : "");
}
}
else
{
_loc8_ = _loc4_;
_loc7_ = _secToEnd[_loc8_] - _loc5_;
_secToEnd[_loc8_] = _loc7_;
if(_secToEnd[_loc4_] <= 0)
{
if(_partiesListLoaded)
{
_ajItemWindows.deleteItem(_loc4_,_partyDefIds);
}
else
{
_partyDefIds.splice(_loc4_,1);
}
_partyMediaIds.splice(_loc4_,1);
_secToStart.splice(_loc4_,1);
_secToEnd.splice(_loc4_,1);
_hours.splice(_loc4_,1);
_mins.splice(_loc4_,1);
if(_loc4_ == 0)
{
_ajItemWindowSingle.destroy();
_ajItemWindowSingle = new ItemWindowParty(onSinglePartyWindowLoaded,null,"",0,ajWinMouseDown,null,null,null,{
"mediaRefId":_partyMediaIds,
"printTimeFunc":getAJWindowPrintTime
});
}
_loc4_--;
}
}
_loc4_++;
}
if(_customPartyData)
{
_loc4_ = 0;
while(_loc4_ < _customPartyData.length)
{
_customPartyData[_loc4_].timeLeft -= _loc5_;
_loc6_ = int(_customPartyData[_loc4_].timeLeft);
if(_loc6_ <= 0)
{
_customPartyItemWindows.deleteItem(_loc4_,_customPartyData);
setupCreateJoinButtonText();
}
else
{
_loc2_ = ItemWindowParty(_customPartyItemWindows.mediaWindows[_loc4_]);
_loc2_.setupTextAndAnims(getCustomWindowPrintTime(_loc6_));
}
_loc4_++;
}
}
if(_numSecPassed == 60)
{
_numSecPassed = 0;
}
}
private function onCustomPartyCreateClose(param1:Boolean = false) : void
{
if(_customPartyCreatePopup)
{
_customPartyCreatePopup.destroy(param1);
_customPartyCreatePopup = null;
}
}
private function onPopup(param1:MouseEvent) : void
{
param1.stopPropagation();
}
protected function onCloseBtn(param1:MouseEvent) : void
{
if(param1)
{
param1.stopPropagation();
}
if(_closeCallback != null)
{
_closeCallback();
}
else
{
destroy();
}
}
private function onOpenPartyTab(param1:MouseEvent) : void
{
param1.stopPropagation();
if(_tabTimeLine)
{
if(_tabTimeLine.reversed())
{
_tabTimeLine.reversed(false);
_tabTimeLine.resume();
}
else
{
_tabTimeLine.reversed(true);
}
}
else
{
_tabTimeLine = new TimelineLite();
_tabTimeLine.add(new TweenLite(_partyPopup.frameDrawerCont,1,{
"x":"+=370",
"ease":Expo.easeInOut
}),0);
_tabTimeLine.add(new TweenLite(_partyPopup,1,{
"x":"-=170",
"ease":Expo.easeInOut
}),0);
}
if(_ajItemWindows == null && !_useMinimalist)
{
buildAJPartyWindows();
}
}
private function onClosePartyTab(param1:MouseEvent) : void
{
param1.stopPropagation();
if(!_tabTimeLine.reversed())
{
_tabTimeLine.reverse();
}
}
private function onThrowPartyBtn(param1:MouseEvent) : void
{
param1.stopPropagation();
if(_customPartyCreatePopup)
{
_customPartyCreatePopup.destroy();
}
_customPartyCreatePopup = new CustomPartyCreatePopup(onCustomPartyCreateClose);
}
private function onHostPartyBtn(param1:MouseEvent) : void
{
var _loc2_:String = null;
var _loc3_:UserInfo = gMainFrame.userInfo.playerUserInfo;
if(_loc3_)
{
if(_loc3_.isStillHosting)
{
_loc2_ = gMainFrame.server.getCurrentRoomName();
if(_loc2_.indexOf("pparty") == -1 || _loc2_.indexOf(_loc3_.userName) == -1)
{
PartyManager.sendCustomPartyJoin(_loc3_.userName,_loc3_.uuid,null);
}
}
}
}
private function singleWinMouseDown(param1:MouseEvent) : void
{
var _loc2_:Object = null;
param1.stopPropagation();
if(param1.currentTarget == _adventureHeaderWindow)
{
DarkenManager.showLoadingSpiral(true);
if(AvatarManager.roomEnviroType == 1)
{
RoomXtCommManager.sendNonDenRoomJoinRequest("adventures.queststaging_421_0_586#" + RoomManagerWorld.instance.shardId);
}
else
{
RoomXtCommManager.sendNonDenRoomJoinRequest("adventures.queststaging_421_0_585#" + RoomManagerWorld.instance.shardId);
}
}
else
{
_loc2_ = _additionalHeaderData[param1.currentTarget.additionalIndex];
if(_loc2_)
{
if(_loc2_.isParty)
{
if(_loc2_.secToStart <= 0)
{
DarkenManager.showLoadingSpiral(true);
PartyXtCommManager.sendJoinPartyRequest(param1.currentTarget.defId);
onCloseBtn(null);
}
else
{
new SBOkPopup(GuiManager.guiLayer,LocalizationManager.translateIdAndInsertOnly(14778,Utility.calculatePrintTime(_loc2_.headerTime.mins,_loc2_.headerTime.hours,true)));
}
}
else
{
DarkenManager.showLoadingSpiral(true);
QuestXtCommManager.sendQuestCreateJoinPublic(param1.currentTarget.defId);
onCloseBtn(null);
}
}
}
}
protected function ajWinMouseDown(param1:MouseEvent) : void
{
param1.stopPropagation();
var _loc2_:int = int(param1.currentTarget.index);
if(_secToStart[_loc2_] - _timeOffset <= 0)
{
if(_secToEnd[_loc2_] <= (getTimer() - _initialTime) / 1000)
{
new SBOkPopup(GuiManager.guiLayer,LocalizationManager.translateIdOnly(14777));
if(_partiesListLoaded)
{
_ajItemWindows.deleteItem(_loc2_,_partyDefIds);
}
else
{
_partyDefIds.splice(_loc2_,1);
}
_partyMediaIds.splice(_loc2_,1);
_secToStart.splice(_loc2_,1);
_secToEnd.splice(_loc2_,1);
_hours.splice(_loc2_,1);
_mins.splice(_loc2_,1);
if(_loc2_ == 0)
{
_ajItemWindowSingle.destroy();
_ajItemWindowSingle = new ItemWindowParty(onSinglePartyWindowLoaded,null,"",0,ajWinMouseDown,null,null,null,{
"mediaRefId":_partyMediaIds,
"printTimeFunc":getAJWindowPrintTime
});
}
return;
}
DarkenManager.showLoadingSpiral(true);
if(param1.currentTarget.isGame)
{
if(MinigameManager.minigameInfoCache.getMinigameInfo(102) == null)
{
MinigameXtCommManager.sendMinigameInfoRequest([102],false,onMinigameInfoResponse);
}
else
{
MinigameManager.handleGameClick({"typeDefId":102},null,true);
}
}
else
{
PartyXtCommManager.sendJoinPartyRequest(param1.currentTarget.defId);
}
onCloseBtn(null);
}
else
{
new SBOkPopup(GuiManager.guiLayer,LocalizationManager.translateIdAndInsertOnly(14778,calculatePrintTime(_loc2_,true)));
}
}
private function customWinMouseDown(param1:MouseEvent) : void
{
var _loc2_:String = null;
var _loc5_:Object = null;
var _loc3_:UserInfo = null;
param1.stopPropagation();
var _loc4_:int = int(param1.currentTarget.index);
if(param1.currentTarget.timeLeft <= 0)
{
new SBOkPopup(GuiManager.guiLayer,LocalizationManager.translateIdOnly(14777));
if(_customPartyItemWindows)
{
_customPartyItemWindows.deleteItem(_loc4_,_customPartyData);
}
else
{
_customPartyData.splice(_loc4_,1);
}
setupCreateJoinButtonText();
}
else
{
_loc2_ = gMainFrame.server.getCurrentRoomName();
_loc5_ = _customPartyData[_loc4_];
_loc3_ = gMainFrame.userInfo.playerUserInfo;
if(_loc2_.indexOf("pparty") == -1 || _loc2_.indexOf(_loc3_.userName) == -1)
{
PartyManager.sendCustomPartyJoin("",_loc5_.creator,_loc5_.nodeId);
}
else if(_loc3_.uuid != _loc5_.creator)
{
PartyManager.sendCustomPartyJoin("",_loc5_.creator,_loc5_.nodeId);
}
}
}
}
}
File diff suppressed because it is too large. Load diff
+17 -2
View File
@@ -192,7 +192,7 @@ package gui
if(_loc4_.masteryCounter >= 100)
{
_inventoryMC.bMastery.visible = true;
_inventoryMC.bMastery.icon.gotoAndStop(PetManager.petNameForDefId(_loc4_.defId) + "1");
showMasteryIcon(PetManager.petNameForDefId(_loc4_.defId) + "1");
if((_loc4_.uBits >> 8 & 0x0F) > 0)
{
_inventoryMC.bMastery.mouse.visible = false;
@@ -230,6 +230,21 @@ package gui
}
}
// the mastery badge has a frame per pet that had a mastery item; this
// server lets any pet reach 100, and a missing frame threw (#2109) and
// left the rest of the inventory unset.
private function showMasteryIcon(param1:String) : void
{
try
{
_inventoryMC.bMastery.icon.gotoAndStop(param1);
}
catch(e:Error)
{
_inventoryMC.bMastery.visible = false;
}
}
// A double click on the big pet's name lets the player type another.
private function onPetRenamed(param1:String) : void
{
@@ -490,7 +505,7 @@ package gui
if(_loc5_.masteryCounter >= 100)
{
_inventoryMC.bMastery.visible = true;
_inventoryMC.bMastery.icon.gotoAndStop(PetManager.petNameForDefId(_loc5_.defId) + "1");
showMasteryIcon(PetManager.petNameForDefId(_loc5_.defId) + "1");
if((_loc5_.uBits >> 8 & 0x0F) > 0)
{
_inventoryMC.bMastery.mouse.visible = false;
+3 -1
View File
@@ -126,9 +126,11 @@ package gui
}
}
// free typing in the chat bar (0) and on Jammer Walls (2), whose posts
// go through each reader's own filter (playerWall.PostMessage).
public function isAllowedFreeChat() : Boolean
{
return _useType == 0 && (gMainFrame.userInfo.sgChatType == 1 && LocalizationManager.currentLanguage == LocalizationManager.accountLanguage && LocalizationManager.currentLanguage == LocalizationManager.LANG_ENG);
return (_useType == 0 || _useType == 2) && (gMainFrame.userInfo.sgChatType == 1 && LocalizationManager.currentLanguage == LocalizationManager.accountLanguage && LocalizationManager.currentLanguage == LocalizationManager.LANG_ENG);
}
public function loadDictionaryBlob() : void
+11 -1
View File
@@ -583,7 +583,11 @@ package shop
_denPreviewManager.destroy();
_denPreviewManager = null;
}
removeListeners();
// a shop replaced before its artwork came has none to unhook (#1009)
if(_shop)
{
removeListeners();
}
if(_shopItemArray && _shopItemArray.length > 0)
{
_loc1_ = 0;
@@ -621,6 +625,12 @@ package shop
TutorialPopups.closeTutorialTextPopup();
_spirals = null;
_closeCallback = null;
if(_shop == null)
{
_shopToSell = null;
_shopWithPreview = null;
return;
}
if(_shop.buyPopup.visible)
{
DarkenManager.unDarken(_shop.buyPopup);
+447
View File
@@ -0,0 +1,447 @@
package game
{
import com.sbi.corelib.audio.SBAudio;
import com.sbi.corelib.audio.SBMusic;
import com.sbi.loader.LoaderCache;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;
import flash.utils.Dictionary;
import flash.utils.getTimer;
public class SoundManager
{
private static const BARWIDTH:int = 136;
public var _musicVolume:Dictionary;
public var _soundVolume:Dictionary;
public var _musicChannel:Dictionary;
public var _soundChannel:Dictionary;
public var _sound:Dictionary;
public var _soundByName:Dictionary;
private var _soundsPlaying:Dictionary;
private var _soundChannelsPlaying:Dictionary;
private var _soundLimit:int;
public var _sounds:Array;
public var _music:Array;
public var _soundToolInstace:MovieClip;
public var _barSound:Dictionary;
public var _minigame:GameBase;
private var _currentDragger:MovieClip;
private var _soundVolumeByName:Dictionary;
private var _lastTimeFadeIn:Number;
private var _lastTimeFadeOut:Number;
private var _fadeInStream:SBMusic;
private var _fadeOutStream:SBMusic;
public function SoundManager(param1:GameBase, param2:int = 0)
{
super();
_musicVolume = new Dictionary(true);
_soundVolume = new Dictionary(true);
_barSound = new Dictionary(true);
_musicChannel = new Dictionary(true);
_soundChannel = new Dictionary(true);
_sound = new Dictionary(true);
_soundByName = new Dictionary(true);
_soundsPlaying = new Dictionary(true);
_soundChannelsPlaying = new Dictionary(true);
_soundVolumeByName = new Dictionary(true);
_sounds = [];
_music = [];
_minigame = param1;
_soundLimit = param2;
if(!MainFrame.isInitialized())
{
LoaderCache.contentURL = "../../";
}
}
public function setVolumes(param1:Dictionary) : void
{
for(var _loc2_:Object in param1)
{
_soundVolumeByName[_loc2_] = param1[_loc2_];
}
}
private function getSound(param1:String) : Object
{
var _loc2_:* = null;
if(param1 == null)
{
return null;
}
for each(_loc2_ in _sounds)
{
if(_loc2_.name == param1)
{
return _loc2_;
}
}
return null;
}
public function addSound(param1:Class, param2:Number, param3:String = null) : void
{
var _loc6_:Object = getSound(param3);
if(_loc6_ == null)
{
_loc6_ = {};
_loc6_.sound = new param1() as Sound;
if(param3)
{
_loc6_.name = param3;
}
_sounds.push(_loc6_);
_sound[param1] = _loc6_.sound;
}
if(param2 >= 0)
{
_soundVolume[_loc6_.sound] = param2;
}
else
{
if(!_soundVolumeByName[param3] || _soundVolumeByName[param3] < 0)
{
trace("Why is " + param3 + "not right in _soundVolumeByName?");
_soundVolumeByName[param3] = 0;
}
_soundVolume[_loc6_.sound] = _soundVolumeByName[param3];
}
_soundsPlaying[_loc6_.sound] = 0;
var _loc5_:SoundTransform = new SoundTransform(0,0);
var _loc4_:SoundChannel = _loc6_.sound.play(0,0,_loc5_);
if(_loc4_)
{
_loc4_.stop();
}
}
public function addSoundByName(param1:Sound, param2:String, param3:Number) : void
{
var _loc6_:Object = getSound(param2);
if(_loc6_ == null)
{
_loc6_ = {};
_loc6_.sound = param1;
_loc6_.name = param2;
_sounds.push(_loc6_);
_soundByName[param2] = param1;
}
if(param3 >= 0)
{
_soundVolume[_loc6_.sound] = param3;
}
else
{
_soundVolume[_loc6_.sound] = _soundVolumeByName[param2];
}
_soundsPlaying[_loc6_.sound] = 0;
var _loc5_:SoundTransform = new SoundTransform(0,0);
var _loc4_:SoundChannel = _loc6_.sound.play(0,0,_loc5_);
if(_loc4_)
{
_loc4_.stop();
}
}
public function addStream(param1:String, param2:Number) : SBMusic
{
var _loc4_:Object = {};
var _loc3_:SBMusic = new SBMusic(param1 + ".mp3",false,param2);
_loc4_.sound = _loc3_;
_loc4_.name = param1;
_musicVolume[_loc4_.sound] = param2;
_music.push(_loc4_);
return _loc4_.sound;
}
public function play(param1:Class, param2:Number = 0, param3:int = 0, param4:* = false) : SoundChannel
{
var _loc5_:Number = NaN;
var _loc7_:SoundTransform = null;
var _loc6_:SoundChannel = null;
var _loc8_:Sound = _sound[param1];
if(_loc8_)
{
if(SBAudio.isMusicMuted)
{
_loc5_ = 0;
}
else
{
_loc5_ = Number(_soundVolume[_loc8_]);
}
_loc7_ = new SoundTransform(_loc5_,0);
if(_soundLimit > 0)
{
if(!param4 && _soundsPlaying[_loc8_] >= _soundLimit && param3 == 0)
{
return null;
}
_loc6_ = _loc8_.play(param2,param3,_loc7_);
if(_loc6_)
{
_soundChannelsPlaying[_loc6_] = _loc8_;
_soundsPlaying[_loc8_]++;
if(param3 == 0)
{
_loc6_.addEventListener("soundComplete",soundComplete);
}
}
return _loc6_;
}
return _loc8_.play(param2,param3,_loc7_);
}
return null;
}
public function playByName(param1:String, param2:Number = 0, param3:int = 0) : SoundChannel
{
var _loc4_:Number = NaN;
var _loc6_:SoundTransform = null;
var _loc5_:SoundChannel = null;
var _loc7_:Sound = _soundByName[param1];
if(_loc7_)
{
if(SBAudio.isMusicMuted)
{
_loc4_ = 0;
}
else
{
_loc4_ = Number(_soundVolume[_loc7_]);
}
_loc6_ = new SoundTransform(_loc4_,0);
if(_soundLimit > 0)
{
if(_soundsPlaying[_loc7_] >= _soundLimit && param3 == 0)
{
return null;
}
_loc5_ = _loc7_.play(param2,param3,_loc6_);
if(_loc5_)
{
_soundChannelsPlaying[_loc5_] = _loc7_;
_soundsPlaying[_loc7_]++;
if(param3 == 0)
{
_loc5_.addEventListener("soundComplete",soundComplete);
}
}
return _loc5_;
}
return _loc7_.play(param2,param3,_loc6_);
}
return null;
}
private function soundComplete(param1:Event) : void
{
param1.target.removeEventListener("soundComplete",soundComplete);
_soundsPlaying[_soundChannelsPlaying[param1.target]]--;
_soundChannelsPlaying[param1.target] = null;
}
private function doFadeIn(param1:Event) : void
{
var _loc4_:Number = (getTimer() - _lastTimeFadeIn) / 1000;
if(_loc4_ >= 1)
{
_loc4_ = 1;
gMainFrame.stage.removeEventListener("enterFrame",doFadeIn);
}
var _loc2_:Number = _musicVolume[_fadeInStream] * _loc4_;
var _loc5_:SoundChannel = _fadeInStream.sc;
var _loc3_:SoundTransform = new SoundTransform(_loc2_,0);
_fadeInStream.sc.soundTransform = _loc3_;
if(_loc4_ == 1)
{
_fadeInStream = null;
}
}
private function doFadeOut(param1:Event) : void
{
var _loc4_:Number = (getTimer() - _lastTimeFadeOut) / 1000;
// the stream went before its fade ended (#1009)
if(_fadeOutStream == null || _fadeOutStream.sc == null)
{
gMainFrame.stage.removeEventListener("enterFrame",doFadeOut);
_fadeOutStream = null;
return;
}
if(_loc4_ >= 1)
{
_loc4_ = 1;
gMainFrame.stage.removeEventListener("enterFrame",doFadeOut);
}
var _loc2_:Number = _musicVolume[_fadeOutStream] * (1 - _loc4_);
var _loc3_:SoundTransform = new SoundTransform(_loc2_,0);
_fadeOutStream.sc.soundTransform = _loc3_;
if(_loc4_ == 1)
{
_fadeOutStream.sc.stop();
_fadeOutStream = null;
}
}
public function destroy(param1:Boolean = true) : void
{
if(_fadeInStream)
{
gMainFrame.stage.removeEventListener("enterFrame",doFadeIn);
_fadeInStream = null;
}
if(_fadeOutStream)
{
if(_fadeOutStream.sc)
{
_fadeOutStream.sc.stop();
}
_fadeOutStream = null;
gMainFrame.stage.removeEventListener("enterFrame",doFadeOut);
}
if(param1)
{
_musicVolume = new Dictionary(true);
_soundVolume = new Dictionary(true);
_barSound = new Dictionary(true);
_musicChannel = new Dictionary(true);
_soundChannel = new Dictionary(true);
_sound = new Dictionary(true);
_soundByName = new Dictionary(true);
_soundsPlaying = new Dictionary(true);
_soundChannelsPlaying = new Dictionary(true);
_soundVolumeByName = new Dictionary(true);
_sounds = [];
_music = [];
}
}
public function fadeOut(param1:SBMusic) : void
{
if(SBAudio.isMusicMuted)
{
param1.stop();
return;
}
_lastTimeFadeOut = getTimer();
_fadeOutStream = param1;
gMainFrame.stage.addEventListener("enterFrame",doFadeOut,false,0,true);
}
public function playStream(param1:SBMusic, param2:Number = 0, param3:int = 0, param4:Boolean = false) : SoundChannel
{
var _loc6_:SoundTransform = null;
if(SBAudio.isMusicMuted)
{
param4 = false;
}
if(param1 == null || _musicVolume[param1] == null)
{
return null;
}
var _loc5_:Number = Number(_musicVolume[param1]);
if(_fadeOutStream == param1)
{
gMainFrame.stage.removeEventListener("enterFrame",doFadeOut);
_loc5_ = Number(_musicVolume[_fadeOutStream]);
_loc6_ = new SoundTransform(_loc5_,0);
if(_fadeOutStream.sc != null)
{
_fadeOutStream.sc.soundTransform = _loc6_;
return _fadeOutStream.sc;
}
return null;
}
if(param4)
{
_loc6_ = new SoundTransform(0,0);
gMainFrame.stage.addEventListener("enterFrame",doFadeIn,false,0,true);
_lastTimeFadeIn = getTimer();
_fadeInStream = param1;
}
else
{
_loc6_ = new SoundTransform(_loc5_,0);
}
param1.stop();
param1.play(param2,param3,_loc6_);
if(param1.sc == null)
{
return null;
}
_musicChannel[param1] = param1.sc;
param1.sc.soundTransform = _loc6_;
if(SBAudio.isMusicMuted)
{
param1.mute();
}
return param1.sc;
}
public function pauseStream(param1:SBMusic) : void
{
param1.pause();
}
public function unpauseStream(param1:SBMusic) : void
{
param1.unpause();
}
public function togglePauseStream(param1:SBMusic) : void
{
param1.togglePause();
}
public function stop(param1:SoundChannel) : void
{
_soundsPlaying[_soundChannelsPlaying[param1]]--;
_soundChannelsPlaying[param1] = null;
param1.stop();
}
private function onPlay(param1:MouseEvent) : void
{
}
private function onStop(param1:MouseEvent) : void
{
}
private function onPlayMusic(param1:MouseEvent) : void
{
}
private function onStopMusic(param1:MouseEvent) : void
{
}
}
}
+1 -1
View File
@@ -204,7 +204,7 @@ package
{
NPCView.disguiseDefId = 0;
GlobalErrorCatch.reportToServer("while handling server message \"" + param1.obj[0] + "\": " + e + "\n" + e.getStackTrace());
throw e;
// not thrown on: the global catch only reported it a second time
}
NPCView.disguiseDefId = 0;
}
BIN
View File
Binary file not shown.
+71
View File
@@ -0,0 +1,71 @@
import com.jpexs.decompiler.flash.SWF;
import com.jpexs.decompiler.flash.abc.ABC;
import com.jpexs.decompiler.flash.abc.ScriptPack;
import com.jpexs.decompiler.flash.abc.avm2.parser.script.AbcIndexing;
import com.jpexs.decompiler.flash.abc.avm2.parser.script.ActionScript3Parser;
import com.jpexs.decompiler.flash.tags.ABCContainerTag;
import com.jpexs.decompiler.flash.tags.Tag;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// adds empty classes to a swf, for `ffdec -replace` to fill in from swf-src/:
// -replace only replaces classes that are there already. each one is an empty
// "package x { public class Y {} }" compiled into the abc that holds the
// game's own classes (the way JPEXS's "Add class" does it); new method bodies
// go on the end, so the places tools/build-client.sh names stay as they are.
// a class the swf has already is left alone. run by tools/build-client.sh as
//
// java -cp tools/ffdec/lib/ffdec_lib.jar tools/AddClass.java <in.swf> <out.swf> <pkg.Class>...
//
// the way of doing it is Strawberry Jam's (scripts/patches/tool/PatchTool.java).
public class AddClass {
public static void main(String[] args) throws Exception {
SWF swf;
try (FileInputStream in = new FileInputStream(args[0])) {
swf = new SWF(in, false);
}
List<ABC> abcs = new ArrayList<>();
for (ABCContainerTag tag : swf.getAbcList()) {
abcs.add(tag.getABC());
}
Set<String> present = new HashSet<>();
ABCContainerTag container = null;
for (ABC abc : abcs) {
for (ScriptPack pack : abc.getScriptPacks(null, abcs)) {
String path = pack.getClassPath().toString();
present.add(path);
// the game's classes all sit in one abc; new ones go beside them
if (container == null && path.equals("AJClient")) {
container = abc.parentTag;
}
}
}
if (container == null) {
throw new IllegalStateException("no AJClient class in " + args[0]);
}
for (int i = 2; i < args.length; i++) {
String fqcn = args[i];
if (present.contains(fqcn)) {
continue;
}
int dot = fqcn.lastIndexOf('.');
String pkg = dot < 0 ? "" : fqcn.substring(0, dot);
String cls = fqcn.substring(dot + 1);
AbcIndexing index = swf.getAbcIndex();
index.selectAbc(container.getABC());
ActionScript3Parser parser = new ActionScript3Parser(index);
parser.addScript("package " + pkg + " { public class " + cls + " { } }", fqcn.replace('.', '/'), 0, 0, swf.getDocumentClass(), container.getABC());
((Tag) container).setModified(true);
swf.clearAllCache();
swf.setModified(true);
System.out.println("added class " + fqcn);
}
try (FileOutputStream out = new FileOutputStream(args[1])) {
swf.saveTo(out);
}
}
}
+35 -3
View File
@@ -12,6 +12,12 @@
# decompiler gets two of that class's functions wrong, so the class cannot
# be compiled from its source. 4839 is that method body's place in the
# untouched client.
#
# gui.BulletinBoard cannot be compiled from its source either (its media
# callback comes out as loops that do not do what the bytecode does), so two
# of its methods are replaced as P-code: the tutorial and "what's new" video
# lists return at once when empty, as this server sends them (they threw).
# 3830 and 3832 are those method bodies' places in the untouched client.
set -e
cd "$(dirname "$(readlink -f "$0")")/.."
out=${1:-swf/ajclient.swf}
@@ -52,13 +58,39 @@ set -- \
avatar.AvatarWorldView AvatarWorldView.as \
room.RoomManagerWorld RoomManagerWorld.as \
gskinner.motion.GTween GTween.as \
playerWall.PostMessage PostMessage.as
playerWall.PostMessage PostMessage.as \
shop.BundleShop BundleShop.as \
gui.GenericListGuiManager GenericListGuiManager.as \
gui.DenSwitcher DenSwitcher.as \
gui.PetCreator PetCreator.as \
gui.NGFactManager NGFactManager.as \
game.distanceChallenge.DistanceChallenge DistanceChallenge.as \
buddy.BuddyList BuddyList.as \
Party.PartyPopup PartyPopup.as \
gui.ECardInbox ECardInbox.as \
game.SoundManager SoundManager.as \
com.sbi.graphics.LayerAnim LayerAnim.as \
com.sbi.graphics.LayerBitmap LayerBitmap.as \
ecard.ECard ECard.as \
game.ArtStudioKit ArtStudioKit.as \
game.artStudioPainting.ArtStudioPainting ArtStudioPainting.as \
game.artStudioGridDrawing.ArtStudioGridDrawing ArtStudioGridDrawing.as
# not in the game: added before the replace (game.ArtStudioKit is Strawberry
# Jam's, shared by its two art studio painters)
NEW_CLASSES="game.ArtStudioKit"
args=""
while [ $# -gt 0 ]; do
args="$args $1 swf-src/$2"
shift 2
done
# classes the game never had (NEW_CLASSES) are added empty first
# (tools/AddClass.java), for the replace to fill in from swf-src/
base=$(mktemp --suffix=.swf)
trap 'rm -f "$base"' EXIT
java -cp "tools/ffdec/lib/*" tools/AddClass.java swf/ajclient.before-finder.swf "$base" $NEW_CLASSES
# shellcheck disable=SC2086
java -jar tools/ffdec/ffdec-cli.jar -replace swf/ajclient.before-finder.swf "$out" \
gui.EmoticonUtility swf-src/EmoticonUtility.cinit.pcode 4839 $args | grep -v "^Replac\|EXPERIMENTAL" || true
java -jar tools/ffdec/ffdec-cli.jar -replace "$base" "$out" \
gui.EmoticonUtility swf-src/EmoticonUtility.cinit.pcode 4839 \
gui.BulletinBoard swf-src/BulletinBoard.onTutorialGLReceived.pcode 3830 \
gui.BulletinBoard swf-src/BulletinBoard.onWhatsNewVideosLoaded.pcode 3832 $args | grep -v "^Replac\|EXPERIMENTAL" || true
ls -l "$out"