diff --git a/wifecraft/README.md b/wifecraft/README.md index b8707d33..214ea4ae 100644 --- a/wifecraft/README.md +++ b/wifecraft/README.md @@ -5,7 +5,7 @@ An Android scene simulation. Choose a location, pick or create NPCs, and select 1. Open **Choose Scene** and pick the Stormwind Embassy. 2. Select up to six NPCs. **Create NPC** saves a character to your roster. NPCs from older projects also appear in the roster. 3. Enable interactions for objects already in the scene. Stormwind Embassy uses its existing study table and books. -4. Begin the scene. NPCs wander until you give them an order (with **Partner** on, two may also start a partner animation together: Sims 4 animations, below). Select an NPC in the room or in the cast bar, then tap an object or choose an interaction. **NPC camera** follows the selected NPC. Drag to orbit and pinch or use the zoom buttons. Tap the floor in **NPC camera** to send the selected NPC there. **Room camera** restores the room view. **End scene** returns to the title. +4. Begin the scene. NPCs wander until you give them an order (with **Partner** on, two may also start a partner animation together: Sims 4 animations, below). The scene fills the screen with its HUD over it, in the menus' look: a top bar (the place, the clock, and the gear for the scene menu: Resume, Options where offered, **End scene**), the cast as party frames (down the left on a wide screen, a strip under the top bar on the cover screen standing; the NPC you control lit gold, their partner in rose), a line of help, and an action bar. Tap an NPC (in the room or their frame) to control them; tap another NPC to make them the partner (the **Partner: name ×** chip clears it); tap the frame again, **Release** or empty floor to let go. The action bar shows six orders at a time (two rows of three on the cover screen standing), with a page button at its end for the rest: **Walk** (the camera follows the NPC; tap the floor to send them there, drag to orbit, pinch or use the zoom buttons), **Play animation**, **Partner animation** (with a partner), **Say…**, **Chat with…**, **Stop repeat** and **Clear queue** while there is one, **Release**, then the scene's objects (**Sit in chair**, **Read a book**...) and **Free will**. Tapping an object in the room still uses it. The Stormwind Embassy uses the existing wago.tools location pack. The title and scene setup use the original Wifecraft menu backdrop. The title emblem and first-launch download art also come from the earlier Wifecraft builds. Warcraft controls and selector icons load from wago.tools. The character, furniture, and book models load through the app's existing wago.tools pipeline. @@ -21,7 +21,7 @@ For WickedWhims, open **Choose objects → Animation library → Import WickedWh From **Choose objects**, open **Animation library** and select **Import rig and clips**. Choose a Sims 4 animation package or its ZIP or 7z archive. The importer can use a humanoid skeleton included in the package. For packs without one, choose an adult Sims 4 skeleton from your game installation. The importer reports which clips it can retarget and lets you review them before saving. -Use **Animation library → Browse animations** to preview imported clips before a scene. Once the scene starts, NPCs wander. Select an NPC, choose **Play animation**, and pick a solo clip or a partner animation. For a partner animation, pick another NPC and the app starts the two roles together after they meet. **Repeat** loops the selected animation until you stop it or queue another clip. **Queue** adds a clip after the current order, and **Queue stages** follows the stages linked by the author. Reinstall WickedWhims to refresh the grouping, stage links, and authored cycle counts for clips already in your library. +Use **Animation library → Browse animations** to preview imported clips before a scene. Once the scene starts, NPCs wander. Select an NPC and choose **Play animation**: a window with category tabs (All, each group, and **Partner**, first while the NPC has a partner), a search and large rows. Pick a row, then **Preview** plays it once at once with the window kept open, and the main button plays, queues or repeats it as the mode row says (**Play now**, **Queue**, **Repeat**, **Queue stages**). For a partner animation, pick another NPC and the app starts the two roles together after they meet. **Repeat** loops the selected animation until you stop it or queue another clip. **Queue** adds a clip after the current order, and **Queue stages** follows the stages linked by the author. Reinstall WickedWhims to refresh the grouping, stage links, and authored cycle counts for clips already in your library. The imported Sims rig supplies the source bone hierarchy, bind transforms, and animation curves. The retargeter converts mapped tracks to Warcraft's coordinates and bind pose so Warcraft mesh skinning stays intact. Source clip timing is retained. Ordinary wandering and furniture commands use Warcraft animations. @@ -29,9 +29,15 @@ The imported Sims rig supplies the source bone hierarchy, bind transforms, and a **Partner animations in the scene.** Every two-person animation plays the same way, whether you chose it with **Play animation**, sent an NPC with **Send to partner**, or two NPCs began one by themselves: both walk to their places around a shared spot, the one waiting turns to face the one coming, and both clips start on the same simulation step and play on one clock, cycle after cycle; the animation's sound events play at their times (Partner sounds, below). By themselves: an idle NPC (not on furniture, not carrying out your order) whose cooldown has passed may go to another idle NPC within six yards (the nearest; a random one of equally near) and play a partner animation picked at random from the enabled ones whose place the scene has (the floor, or the couch, bed or chair it was made for); with none that fits, both play one Warcraft emote their models share (wave, cheer, dance, laugh, bow, kiss, applaud or salute) facing each other. A looping one repeats 1 to 4 times or for 6 to 25 seconds; then both step apart and wait 20 to 60 seconds before doing it again. In **Choose objects**, **Partner** sets how often: Off, Sometimes (the default) or Often, and the row under it counts the partner animations available. **Send to partner** (select an NPC, press it, tap another NPC) sends the selected NPC to start one with that NPC. The cast bar shows "With " for both, and the line under the orders names the animation. Your orders to either NPC and **End scene** interrupt it; the other NPC goes back to idle at once. The simulation is unit-tested on the desktop with fake animations (`simulation/PartnerActivityTest`, `PerformanceTest`); the screens are compiled by CI only, and none of it has run on a phone. +## Music, sounds and the menus + +The title, Gathering the Files, the scene's setup, the live scene's HUD (top bar, party frames, action bar, speech bubbles, the Play animation window and its lists), the animation library's page, Options and Updates use the current game's look: dark slate panels with a thin gold trim, rounded buttons that glow when pressed (or hovered with a mouse or stylus), a backdrop that breathes slowly with motes rising over it (still when the phone's animations are off). The character creator keeps its own look. + +The menus play the title music of The War Within (MUS_110_MAIN_TITLE); a live scene plays its place's own music and ambience from the game's tables (the Stormwind Embassy: its room's ZoneMusic 1929, six tracks one after another with a short gap, and SoundAmbience 569's day or night loop), crossfading between them. The music dips while an emote's voice or a partner sound plays. Buttons, tabs, switches and windows play the game's interface sounds (SoundKitConstants: IG_MAINMENU_OPEN/CLOSE/OPTION, GS_TITLE_OPTION_OK, IG_CHARACTER_INFO_TAB...). Options > Sound has Enable Sound, Master, Music, Ambience, Sound effects and Dialog, as the game's Sound page; everything is silent while Wifecraft is in the background. The files are the game's, by id (`assets/sounds.json`, made by `tools/sounds.py`), fetched from wago.tools as they are first played once the files have been gathered; a file that can't be fetched leaves silence and is tried again later. The decisions (mixer, ducking, crossfade, which music where, the sound ids) are unit-tested (`audio/Soundscape.kt`); the playback is compiled by CI only and nobody has listened to it on a phone. + ## Partner sounds -Options > Game > Partner sounds plays sounds with partner animations from the user's own files. A clip's sound event carries a sound name; put audio files (ogg, wav, mp3, m4a, aac, flac), single or in a zip, through Add sounds, named after those names (the exact name, the name without a `vo_` or `sfx_` prefix, numbered variants `name_01`, `name_02` of which one is picked at random, a file named by the name's 32- or 64-bit FNV-1a hash in hex, or a file called `default` for the rest). A sound with no file is simply silent. The files are kept in `files/partner-sounds`; there is an On box, a volume and Remove all. The game's own EA audio (SNR/SNS) is not decoded yet. The folder (`audio/PartnerSounds`, `SoundNames`) is unit-tested; the playback (`SceneAudio.partnerSound`) and the Options rows are compiled by CI only and have not run on a phone. +Options > Sound > Partner sounds plays sounds with partner animations from the user's own files. A clip's sound event carries a sound name; put audio files (ogg, wav, mp3, m4a, aac, flac), single or in a zip, through Add sounds, named after those names (the exact name, the name without a `vo_` or `sfx_` prefix, numbered variants `name_01`, `name_02` of which one is picked at random, a file named by the name's 32- or 64-bit FNV-1a hash in hex, or a file called `default` for the rest). A sound with no file is simply silent. The files are kept in `files/partner-sounds`; there is an On box, a volume and Remove all. The game's own EA audio (SNR/SNS) is not decoded yet. The folder (`audio/PartnerSounds`, `SoundNames`) is unit-tested; the playback (`SceneAudio.partnerSound`) and the Options rows are compiled by CI only and have not run on a phone. ## Building diff --git a/wifecraft/android/app/src/main/AndroidManifest.xml b/wifecraft/android/app/src/main/AndroidManifest.xml index 40fc8034..63534e80 100644 --- a/wifecraft/android/app/src/main/AndroidManifest.xml +++ b/wifecraft/android/app/src/main/AndroidManifest.xml @@ -12,6 +12,7 @@ +#include +#include +#include +#include + +#include "m2.h" +#include "wmath.h" + +namespace wc { + +// An imported animation on a person: each track replaces one bone's local rotation (x,y,z,w about its pivot, in its +// parent's frame: at rest every M2 bone's is the identity, so the model's axes) or translation (model units, given for +// kAnimRootHeight and scaled to the model's own Root). Times in seconds. +struct BoneAnimTrack { + std::string bone; + bool rotation = true; + std::vector times; + std::vector values; // 4 per time (rotation) or 3 (position) +}; +struct BoneAnim { + std::vector tracks; + float duration = 0; // seconds; 0 or one key: a held pose + bool loop = false; // otherwise the last key holds +}; + +// The key pair around `t` (seconds) and how far between them it is. With `loopLen` (a looping clip's length, 0: none) +// longer than the last key, a moment past the last key moves on toward the first, which comes again at `loopLen`: no +// hitch where the clip comes round. Otherwise the first and the last key hold outside the keys. +inline void boneKeys(const std::vector& times, float t, float loopLen, size_t& a, size_t& b, float& f) { + a = b = 0; f = 0; + if (times.empty()) return; + size_t last = times.size() - 1; + if (times.size() == 1 || !(t > times[0])) return; + if (t >= times[last]) { + a = b = last; + if (loopLen > times[last] + 1e-4f && times[0] <= 1e-4f && t < loopLen) { b = 0; f = (t - times[last]) / (loopLen - times[last]); } + return; + } + size_t lo = 0, hi = last; + while (hi - lo > 1) { size_t mid = (lo + hi) / 2; if (times[mid] <= t) lo = mid; else hi = mid; } + a = lo; b = hi; + float span = times[b] - times[a]; + f = span > 0 ? (t - times[a]) / span : 0; +} + +// The rest directions the importer converted every clip for (anim/Retarget: assets/sims_profile.json's wowRest, written by +// tools/wow_bones.py from the night elf woman, 921844): each bone toward the bone it aims at, in model axes. The unit +// tests check this table against the profile (BoneAnimRestTableTest). +struct AnimRest { const char* bone; const char* aim; float x, y, z; }; +inline const AnimRest kAnimRest[] = { + {"Spine1", "Spine2", -0.0789f, 0.0f, 0.9969f}, + {"Spine2", "Chest", 0.0f, 0.0f, 1.0f}, + {"Chest", "Neck1", -0.1289f, 0.0f, 0.9917f}, + {"Neck1", "Head", 0.1717f, 0.0f, 0.9852f}, + {"L_Clavicle", "L_UpperArm", -0.4093f, 0.8902f, 0.2f}, + {"L_UpperArm", "L_Forearm", -0.0257f, 0.8369f, -0.5467f}, + {"L_Forearm", "L_Hand", 0.1785f, 0.8212f, -0.542f}, + {"L_Hand", "L_Middle1", 0.3139f, 0.8717f, -0.3763f}, + {"L_Thumb1", "L_Thumb2", 0.4717f, 0.5155f, -0.7154f}, + {"L_Index1", "L_Index2", 0.2374f, 0.6685f, -0.7048f}, + {"L_Middle1", "L_Middle2", 0.1899f, 0.5686f, -0.8004f}, + {"L_Ring1", "L_Ring2", 0.1363f, 0.5218f, -0.8421f}, + {"L_Pinky1", "L_Pinky2", 0.1208f, 0.6607f, -0.7408f}, + {"L_Thigh", "L_Calf", -0.0424f, 0.0852f, -0.9955f}, + {"L_Calf", "L_Foot", -0.1563f, 0.081f, -0.9844f}, + {"L_Foot", "L_Toe", 0.9381f, 0.004f, -0.3463f}, + {"R_Clavicle", "R_UpperArm", -0.4093f, -0.8902f, 0.2f}, + {"R_UpperArm", "R_Forearm", -0.0257f, -0.8369f, -0.5467f}, + {"R_Forearm", "R_Hand", 0.1785f, -0.8212f, -0.542f}, + {"R_Hand", "R_Middle1", 0.3139f, -0.8717f, -0.3762f}, + {"R_Thumb1", "R_Thumb2", 0.4717f, -0.5155f, -0.7154f}, + {"R_Index1", "R_Index2", 0.2374f, -0.6685f, -0.7048f}, + {"R_Middle1", "R_Middle2", 0.1899f, -0.5686f, -0.8004f}, + {"R_Ring1", "R_Ring2", 0.1363f, -0.5218f, -0.8421f}, + {"R_Pinky1", "R_Pinky2", 0.1208f, -0.6607f, -0.7408f}, + {"R_Thigh", "R_Calf", -0.0424f, -0.0836f, -0.9956f}, + {"R_Calf", "R_Foot", -0.1564f, -0.0804f, -0.9844f}, + {"R_Foot", "R_Toe", 0.9381f, -0.004f, -0.3463f}, +}; + +inline Quat quatMul(const Quat& a, const Quat& b) { + return Quat(a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, + a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z); +} +inline Quat quatInv(const Quat& a) { return Quat(-a.x, -a.y, -a.z, a.w); } +// The shortest turn taking direction `from` onto direction `to` (both unit). +inline Quat quatArc(V3 from, V3 to) { + float d = from.dot(to); + if (d < -0.999999f) { + V3 axis = V3(1, 0, 0).cross(from); + if (axis.dot(axis) < 1e-6f) axis = V3(0, 1, 0).cross(from); + axis = axis.normalized(); + return Quat(axis.x, axis.y, axis.z, 0); + } + V3 c = from.cross(to); + return Quat(c.x, c.y, c.z, 1 + d).normalized(); +} + +// Fits a clip converted for the reference skeleton to `m`: a bone whose rest direction on this model (its pivot toward +// its aim's) differs from the reference's (kAnimRest) is turned by the difference, R = arc(model's, reference's), and its +// key becomes inv(R_parent) * key * R, the parent being the nearest bone above it in the model that a rotation track of +// the clip drives. The clip's pose then lands on this model's limbs as on the reference's (a human's shoulders sit 25 +// degrees from a night elf's at rest: unfitted, the arms of every clip came out that far off). Returns the tracks turned. +inline int fitBoneAnim(BoneAnim& anim, const M2Model& m) { + // the clip's own rotation tracks: a bone whose aim has none was converted without the rest turn (Retarget's Q) + std::map rotated; + for (const BoneAnimTrack& t : anim.tracks) if (t.rotation) rotated[t.bone] = true; + std::map fix; + for (const AnimRest& r : kAnimRest) { + if (!rotated.count(r.bone) || !rotated.count(r.aim)) continue; + int i = m.findWowBone(r.bone), j = m.findWowBone(r.aim); + if (i < 0 || j < 0) continue; + V3 d = m.bones[size_t(j)].pivot - m.bones[size_t(i)].pivot; + if (d.length() < 1e-5f) continue; + Quat q = quatArc(d.normalized(), V3(r.x, r.y, r.z).normalized()); + if (std::fabs(q.w) < 0.99999f) fix[r.bone] = q; // more than about half a degree + } + if (fix.empty()) return 0; + std::map driven; // model bone -> the rotation track's name + for (const BoneAnimTrack& t : anim.tracks) { + if (!t.rotation) continue; + int b = m.findWowBone(t.bone); + if (b >= 0) driven.emplace(b, t.bone); + } + int turned = 0; + for (BoneAnimTrack& t : anim.tracks) { + if (!t.rotation || t.values.size() < t.times.size() * 4) continue; + int b = m.findWowBone(t.bone); + if (b < 0) continue; + std::string parent; + for (int i = m.bones[size_t(b)].parent, guard = 0; i >= 0 && size_t(i) < m.bones.size() && guard < 256; i = m.bones[size_t(i)].parent, ++guard) { + auto it = driven.find(i); + if (it != driven.end()) { parent = it->second; break; } + } + auto own = fix.find(t.bone); + auto up = parent.empty() ? fix.end() : fix.find(parent); + if (own == fix.end() && up == fix.end()) continue; + Quat r = own == fix.end() ? Quat() : own->second; + Quat pi = up == fix.end() ? Quat() : quatInv(up->second); + for (size_t k = 0; k < t.times.size(); ++k) { + float* v = &t.values[k * 4]; + Quat q = quatMul(quatMul(pi, Quat(v[0], v[1], v[2], v[3]).normalized()), r).normalized(); + v[0] = q.x; v[1] = q.y; v[2] = q.z; v[3] = q.w; + } + // keep neighbouring keys on the same side (a turn and its negation are the same turn; slerp takes the short way) + for (size_t k = 1; k < t.times.size(); ++k) { + float* p = &t.values[(k - 1) * 4]; + float* v = &t.values[k * 4]; + if (p[0] * v[0] + p[1] * v[1] + p[2] * v[2] + p[3] * v[3] < 0) for (int c = 0; c < 4; ++c) v[c] = -v[c]; + } + ++turned; + } + return turned; +} + +} // namespace wc diff --git a/wifecraft/android/app/src/main/cpp/engine/m2.cpp b/wifecraft/android/app/src/main/cpp/engine/m2.cpp index b27e330e..be77e473 100644 --- a/wifecraft/android/app/src/main/cpp/engine/m2.cpp +++ b/wifecraft/android/app/src/main/cpp/engine/m2.cpp @@ -430,9 +430,11 @@ V3 spline(int interpolation, V3 p0, V3 out0, V3 in1, V3 p1, float f) { // Keys by the track's interpolation: 0 none (a key holds until the next), 1 linear, 2 Hermite, 3 Bezier (the last two // keep the value and two tangents per key). -V3 M2Model::evalV3(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, V3 def, bool looping) const { +V3 M2Model::evalV3(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, V3 def, bool looping, bool* keyed) const { const uint8_t* d; size_t n; uint32_t tsOff, valOff, count, time, loop; - if (!keys(t, seq, timeMs, globalMs, d, n, tsOff, valOff, count, time, &loop, looping)) return def; + bool has = keys(t, seq, timeMs, globalMs, d, n, tsOff, valOff, count, time, &loop, looping); + if (keyed) *keyed = has; + if (!has) return def; Reader r(d, n); uint32_t a, b; float f; bracket(r, tsOff, count, time, a, b, f, loop); @@ -443,9 +445,11 @@ V3 M2Model::evalV3(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs return lerp(at(a, 0), at(b, 0), f); } -Quat M2Model::evalQuat(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, bool looping) const { +Quat M2Model::evalQuat(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, bool looping, bool* keyed) const { const uint8_t* d; size_t n; uint32_t tsOff, valOff, count, time, loop; - if (!keys(t, seq, timeMs, globalMs, d, n, tsOff, valOff, count, time, &loop, looping)) return Quat(); + bool has = keys(t, seq, timeMs, globalMs, d, n, tsOff, valOff, count, time, &loop, looping); + if (keyed) *keyed = has; + if (!has) return Quat(); Reader r(d, n); uint32_t a, b; float f; bracket(r, tsOff, count, time, a, b, f, loop); @@ -469,19 +473,60 @@ float M2Model::evalShort(const M2Track& t, int seq, uint32_t timeMs, uint32_t gl return t.interpolation == 0 ? va : va + (vb - va) * f; } -void M2Model::pose(int seq, uint32_t timeMs, uint32_t globalMs, std::vector& out, bool looping) const { +void M2Model::pose(int seq, uint32_t timeMs, uint32_t globalMs, std::vector& out, bool looping, + const std::vector* base) const { out.resize(bones.size()); // a sequence the parent skeleton plays moves the bones by the parent's tracks (the same bones, in the same order) int d = dataSequence(seq); bool fromParent = d >= 0 && size_t(d) < sequences.size() && sequences[d].src == 2 && parent_.bones.size() == bones.size(); + // a layer over `base`: a bone the layer has no rotation keys for keeps base's whole pose (never the bind pose) + const std::vector* under = base && base != &out && base->size() == bones.size() && isLayer(seq) ? base : nullptr; for (size_t i = 0; i < bones.size(); ++i) { const M2Bone& b = fromParent ? parent_.bones[i] : bones[i]; + bool keyed = true; + Quat r = evalQuat(b.rotation, seq, timeMs, globalMs, looping, under ? &keyed : nullptr); + if (under && !keyed) { out[i] = (*under)[i]; continue; } + out[i].r = r; out[i].t = evalV3(b.translation, seq, timeMs, globalMs, V3(0, 0, 0), looping); - out[i].r = evalQuat(b.rotation, seq, timeMs, globalMs, looping); out[i].s = evalV3(b.scale, seq, timeMs, globalMs, V3(1, 1, 1), looping); } } +bool M2Model::boneKeyed(int bone, int seq) const { + if (bone < 0 || size_t(bone) >= bones.size()) return false; + int d = dataSequence(seq); + if (d < 0 || size_t(d) >= sequences.size()) return false; + bool fromParent = sequences[d].src == 2 && parent_.bones.size() == bones.size(); + const M2Track& t = (fromParent ? parent_.bones[size_t(bone)] : bones[size_t(bone)]).rotation; + if (t.globalSeq != 0xFFFF) return false; // a global loop's keys aren't the sequence's + const uint8_t* data; size_t n; uint32_t tsOff, valOff, count, time; + return keys(t, seq, 0, 0, data, n, tsOff, valOff, count, time); +} + +namespace { +// The body's main bones (WoW-side names), what isLayer measures a sequence by. +const char* const kLayerBones[] = {"Pelvis", "Spine1", "Chest", "Neck1", "Head", "L_Clavicle", "R_Clavicle", "L_UpperArm", + "R_UpperArm", "L_Forearm", "R_Forearm", "L_Hand", "R_Hand", "L_Thigh", "R_Thigh", "L_Calf", "R_Calf", "L_Foot", "R_Foot"}; +} + +bool M2Model::isLayer(int seq) const { + int d = dataSequence(seq); + if (d < 0 || size_t(d) >= sequences.size() || !sequenceReady(d)) return false; + auto it = layers_.find(d); + if (it != layers_.end()) return it->second; + int found = 0, bare = 0; + for (const char* name : kLayerBones) { + int b = findWowBone(name); + if (b < 0) continue; + ++found; + if (!boneKeyed(b, d)) ++bare; + } + // a creature's skeleton names too few of these to tell: never a layer + bool layer = found >= 8 && bare * 4 >= found; + layers_[d] = layer; + return layer; +} + void M2Model::bonesToMatrices(const std::vector& poses, std::vector& out) const { size_t n = bones.size(); out.assign(n, M4()); diff --git a/wifecraft/android/app/src/main/cpp/engine/m2.h b/wifecraft/android/app/src/main/cpp/engine/m2.h index 2dbfd4ff..58883a38 100644 --- a/wifecraft/android/app/src/main/cpp/engine/m2.h +++ b/wifecraft/android/app/src/main/cpp/engine/m2.h @@ -144,7 +144,16 @@ class M2Model { // The local pose of every bone at `timeMs` into sequence `seq` (`globalMs` drives looping // effects that run on their own clock). `looping`: past a track's last key the pose moves on toward its first (the // game's keys often end before the sequence does), so a loop has no seam; otherwise the last key holds. - void pose(int seq, uint32_t timeMs, uint32_t globalMs, std::vector& out, bool looping = false) const; + // `base`: a layer's ([isLayer]) other bones (those it has no keys for) take their pose from `base` (the pose it is + // played over) instead of the bind pose; null, or a sequence that is no layer: every bone from `seq`'s own tracks. + void pose(int seq, uint32_t timeMs, uint32_t globalMs, std::vector& out, bool looping = false, + const std::vector* base = nullptr) const; + // Whether bone `bone`'s rotation has keys of its own in sequence `seq` (false while its .anim isn't loaded). + bool boneKeyed(int bone, int seq) const; + // A layer: a sequence (its keys loaded) that keys only part of the body, made to be played over another (FacePose: + // the face; HandsClosed: the hands; Stop: the arms). Played alone, the body bones it leaves out would stand in the + // bind pose, arms out. Measured on the body's main bones (kLayerBones in m2.cpp): a quarter or more without keys. + bool isLayer(int seq) const; // The sequences of the same animation as `seq` (its variations, `seq` included), in the file's order. std::vector variations(int seq) const; // Turns local poses into each bone's matrix in model space. @@ -187,8 +196,10 @@ class M2Model { bool keys(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, const uint8_t*& data, size_t& dataSize, uint32_t& tsOff, uint32_t& valOff, uint32_t& count, uint32_t& time, uint32_t* loop = nullptr, bool looping = false) const; - V3 evalV3(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, V3 def, bool looping = false) const; - Quat evalQuat(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, bool looping = false) const; + // `keyed` (if given): whether the track had keys for this moment (false: `def`, or the identity, was returned). + V3 evalV3(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, V3 def, bool looping = false, bool* keyed = nullptr) const; + Quat evalQuat(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, bool looping = false, bool* keyed = nullptr) const; + mutable std::map layers_; // isLayer's answers, by data sequence (asked once its keys are in) float evalShort(const M2Track& t, int seq, uint32_t timeMs, uint32_t globalMs, float def) const; }; diff --git a/wifecraft/android/app/src/main/cpp/engine/scene.cpp b/wifecraft/android/app/src/main/cpp/engine/scene.cpp index 1d9fba72..f2044027 100644 --- a/wifecraft/android/app/src/main/cpp/engine/scene.cpp +++ b/wifecraft/android/app/src/main/cpp/engine/scene.cpp @@ -883,6 +883,7 @@ int Scene::setBoneAnim(int id, const BoneAnim& anim, uint32_t nowMs) { Actor& a = it->second; const M2Model& m = *a.mesh->model; a.boneAnim = std::make_shared(anim); + fitBoneAnim(*a.boneAnim, m); // converted for the reference skeleton's rest pose: turned to this model's a.boneAnimBones.clear(); a.boneAnimRest.assign(m.bones.size(), 0); int found = 0; @@ -926,22 +927,6 @@ void Scene::clearBoneAnim(int id) { it->second.boneAnimRest.clear(); } -namespace { - -// The key pair around `t` (seconds) and how far between them it is. -void boneKeys(const std::vector& times, float t, size_t& a, size_t& b, float& f) { - size_t last = times.size() - 1; - if (times.size() == 1 || t <= times[0]) { a = b = 0; f = 0; return; } - if (t >= times[last]) { a = b = last; f = 0; return; } - size_t lo = 0, hi = last; - while (hi - lo > 1) { size_t mid = (lo + hi) / 2; if (times[mid] <= t) lo = mid; else hi = mid; } - a = lo; b = hi; - float span = times[b] - times[a]; - f = span > 0 ? (t - times[a]) / span : 0; -} - -} // namespace - void Scene::applyBoneAnim(Actor& a, uint32_t now) { if (!a.boneAnim) return; const BoneAnim& an = *a.boneAnim; @@ -954,7 +939,7 @@ void Scene::applyBoneAnim(Actor& a, uint32_t now) { if (b < 0 || size_t(b) >= a.pa.size()) continue; const BoneAnimTrack& tr = an.tracks[k]; size_t ka, kb; float f; - boneKeys(tr.times, t, ka, kb, f); + boneKeys(tr.times, t, an.loop ? an.duration : 0.0f, ka, kb, f); if (tr.rotation) { const float* qa = &tr.values[ka * 4]; const float* qb = &tr.values[kb * 4]; @@ -1037,7 +1022,24 @@ void Scene::animate(Actor& a, uint32_t now) { } a.animTime = t; // a sequence without its keys would be the bind pose: the pose last drawn holds instead - if (m.sequenceReady(a.seq) || !a.posed || a.pa.size() != m.bones.size()) m.pose(a.seq, t, now, a.pa, a.loop); + if (m.sequenceReady(a.seq) && m.isLayer(a.seq)) { + // a layer (FacePose, HandsClosed...) keys part of the body: the rest stands as the idle does (else the pose + // last drawn), never in the bind pose with its arms out + int idle = m.findSequence(a.idleAnim); + if (idle < 0) idle = m.findSequence(0); + if (idle >= 0) m.ensureSequence(idle, files_); + if (idle >= 0 && idle != a.seq && m.sequenceReady(idle) && !m.isLayer(idle)) { + uint32_t idur = std::max(1, m.sequences[size_t(idle)].duration); + m.pose(idle, (now - a.start) % idur, now, a.pl, true); + } else if (a.posed && a.pa.size() == m.bones.size()) { + a.pl = a.pa; + } else { + a.pl.assign(m.bones.size(), BonePose()); + } + m.pose(a.seq, t, now, a.pa, a.loop, &a.pl); + } else if (m.sequenceReady(a.seq) || !a.posed || a.pa.size() != m.bones.size()) { + m.pose(a.seq, t, now, a.pa, a.loop); + } } applyBoneAnim(a, now); // a change of animation: from the pose last drawn to this one, eased in and out; turns by slerp, the rest linearly diff --git a/wifecraft/android/app/src/main/cpp/engine/scene.h b/wifecraft/android/app/src/main/cpp/engine/scene.h index b7d69763..525789d6 100644 --- a/wifecraft/android/app/src/main/cpp/engine/scene.h +++ b/wifecraft/android/app/src/main/cpp/engine/scene.h @@ -11,6 +11,7 @@ #include #include +#include "boneanim.h" #include "location.h" #include "m2.h" #include "skin.h" @@ -38,21 +39,6 @@ struct DressModel { // The look's layer that is the body options' design (creator/LookResolver.BODY_LAYER), not a layer of the skin. constexpr int kBodyLayer = 100; -// An imported animation on a person (anim/Anim, by WoW-side bone names): each track replaces one bone's local -// rotation (x,y,z,w about its pivot, in its parent's frame: at rest every M2 bone's is the identity, so the model's -// axes) or translation (model units, given for kAnimRootHeight and scaled to the model's own Root). Times in seconds. -struct BoneAnimTrack { - std::string bone; - bool rotation = true; - std::vector times; - std::vector values; // 4 per time (rotation) or 3 (position) -}; -struct BoneAnim { - std::vector tracks; - float duration = 0; // seconds; 0 or one key: a held pose - bool loop = false; // otherwise the last key holds -}; - struct Light { float skyTop[3] = {0.25f, 0.38f, 0.66f}; float skyHorizon[3] = {0.72f, 0.78f, 0.86f}; @@ -316,6 +302,7 @@ class Scene { // fadeMs from fadeStart. std::vector pa, pb; bool posed = false; // pa holds a drawn pose (something to blend from) + std::vector pl; // what a layer (M2Model::isLayer) is played over: the idle's pose this frame std::vector mats; // The imported animation (setBoneAnim): its tracks' bones (-1: none here), the bones held at rest under it. std::shared_ptr boneAnim; diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/MainActivity.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/MainActivity.kt index 295eaa4c..8210e926 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/MainActivity.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/MainActivity.kt @@ -33,8 +33,11 @@ import com.logie.wifecraft.ui.RigStore import com.logie.wifecraft.ui.SceneAnimationScreen import com.logie.wifecraft.audio.Audio import com.logie.wifecraft.audio.SceneAudio -import com.logie.wifecraft.audio.SoundVolumes +import com.logie.wifecraft.audio.MixLevels +import com.logie.wifecraft.audio.MixSettings +import com.logie.wifecraft.audio.Mixer import com.logie.wifecraft.simulation.PartnerFrequency +import com.logie.wifecraft.simulation.ChatterFrequency import com.logie.wifecraft.anim.PairAnim import com.logie.wifecraft.anim.animationChoices import com.logie.wifecraft.simulation.PartnerPair @@ -72,10 +75,8 @@ import com.logie.wifecraft.ui.DownloadOptions import com.logie.wifecraft.ui.ImportsSection import com.logie.wifecraft.ui.LocalWar import com.logie.wifecraft.ui.WarArt -import com.logie.wifecraft.ui.WowWindow -import com.logie.wifecraft.ui.RedButton +import com.logie.wifecraft.ui.WifeMessage import com.logie.wifecraft.ui.frizStyle -import androidx.compose.foundation.layout.widthIn import androidx.compose.ui.unit.sp import com.logie.wifecraft.ui.GatherScreen import com.logie.wifecraft.ui.LiveSceneScreen @@ -117,6 +118,9 @@ class MainActivity : ComponentActivity() { private var audio: Audio? = null private lateinit var locationLoader: LocationLoader private var sceneAudio: SceneAudio? = null + private lateinit var mixSettings: MixSettings + /** The Sound page's levels (Options), kept by [mixSettings]. */ + private var mix = MixLevels() private val rosterFile by lazy { AtomicFile(File(filesDir, "npc-roster.json")) } private val animationDirectory by lazy { File(filesDir, "anims") } @@ -142,14 +146,17 @@ class MainActivity : ComponentActivity() { listfile = ListfileNames(File(filesDir, "cache/listfile-character.csv")) imports = ImportStore(filesDir, listfile, supportedKinds = setOf(ImportKind.RALIA, ImportKind.BODY, ImportKind.UNDEAD)) dresser = Dresser(files, tables, imports, lifecycleScope) - audio = runCatching { Audio(applicationContext, files) }.getOrNull()?.apply { - musicVolume = settings.musicVolume / 100f - soundVolume = settings.soundVolume / 100f - } + mixSettings = MixSettings(applicationContext) + mix = mixSettings.load() + audio = runCatching { Audio(applicationContext, files) }.getOrNull() locationLoader = LocationLoader(applicationContext, files, lifecycleScope) sceneAudio = runCatching { SceneAudio(applicationContext, files, tables) }.getOrNull() - applySceneVolumes() - sceneAudio?.apply { partnerOn = settings.partnerSoundsOn; partnerVolume = settings.partnerSoundVolume / 100f } + applyMix(mix) + sceneAudio?.apply { + partnerOn = settings.partnerSoundsOn; partnerVolume = settings.partnerSoundVolume / 100f + // the music and the ambience dip while an emote's voice or a partner sound plays + onVoices = { n -> audio?.voices(n) } + } setContent { App() } } @@ -175,10 +182,11 @@ class MainActivity : ComponentActivity() { super.onDestroy() } - /** Options' volumes on the scene's sounds: music, ambience, effects (Sounds) and voices, each its own. */ - private fun applySceneVolumes() { - val s = settings.soundVolume / 100f - sceneAudio?.volumes = SoundVolumes(music = settings.musicVolume / 100f, ambience = settings.ambienceVolume / 100f, effects = s, voices = settings.voiceVolume / 100f) + /** The Sound page's levels on everything that plays: the soundscape (Audio) and the scene's sounds (SceneAudio). */ + private fun applyMix(m: MixLevels) { + mix = m + audio?.levels = m + sceneAudio?.volumes = Mixer.sceneVolumes(m) } private fun sceneView(): SceneView = scene ?: SceneView(this, files.dir.path).also { scene = it; it.softBody(Settings(this).softBody) } @@ -233,7 +241,7 @@ class MainActivity : ComponentActivity() { // set from the download's threads once per file; read only by the Options panel's host, at most 4 times a second val downloadProgress = remember { MutableStateFlow(null) } var speed by remember { mutableIntStateOf(settings.downloadSpeed) } - var effects by remember { mutableIntStateOf(settings.soundVolume) } + var mixShown by remember { mutableStateOf(mix) } var downloadStatus by remember { mutableStateOf(null) } var downloadJob by remember { mutableStateOf(null) } @@ -267,6 +275,7 @@ class MainActivity : ComponentActivity() { // the library's partner animations, read again whenever the setup, the animation or the live screens open (as the clips are) var pairs by remember { mutableStateOf(emptyList()) } var partnerFrequency by remember { mutableStateOf(PartnerFrequency.of(settings.partnerFrequency)) } + var chatterFrequency by remember { mutableStateOf(ChatterFrequency.of(settings.chatterFrequency)) } var partnerOn by remember { mutableStateOf(settings.partnerSoundsOn) } var partnerVolume by remember { mutableIntStateOf(settings.partnerSoundVolume) } val partnerSink = remember { @@ -309,6 +318,8 @@ class MainActivity : ComponentActivity() { if (catalog == null && GameFiles.TABLES in complete) { catalog = withContext(Dispatchers.Default) { runCatching { Catalog.build(tables) }.getOrNull() } } + // the player has gathered the game's files: the music and sounds not here yet may be fetched as they are wanted + if ("interface" in complete || GameFiles.TABLES in complete) audio?.fetchAllowed = true if ("sound" in complete) audio?.filesArrived() } LaunchedEffect(Unit) { @@ -319,6 +330,11 @@ class MainActivity : ComponentActivity() { } LaunchedEffect(art != null) { if (art != null) menuArt.start() } + // the soundscape follows the screen: the title's music on the menus, a place's music and ambience in its live scene + LaunchedEffect(screen, location) { + val a = audio ?: return@LaunchedEffect + if (screen == Screen.LIVE) a.place(location ?: "") else a.title() + } CompositionLocalProvider(LocalArt provides art, LocalWar provides menuArt, LocalSounds provides { name: String -> audio?.ui(name) }) { Box(Modifier.fillMaxSize()) { when (screen) { @@ -381,6 +397,8 @@ class MainActivity : ComponentActivity() { onAnimations = { screen = Screen.ANIMATIONS }, partner = partnerFrequency, onPartner = { partnerFrequency = it; settings.partnerFrequency = it.name }, + chatter = chatterFrequency, + onChatter = { chatterFrequency = it; settings.chatterFrequency = it.name }, partnerPairs = remember(pairs, availableClips) { pairs.count { it.enabled } + animationChoices(availableClips).count { PartnerPair.of(it) != null } }, @@ -624,9 +642,11 @@ class MainActivity : ComponentActivity() { clips = availableClips, pairs = pairs, partner = partnerFrequency, + chatter = chatterFrequency, fetchAnim = { key, anim -> dresser.fetchAnim(key, anim) }, partnerSounds = partnerSink, onEnd = { screen = Screen.TITLE }, + onSettings = { panel = Panel.OPTIONS }, ready = locationResult == true && loadedActors == chosen.size, status = liveStatus, ) } @@ -650,12 +670,11 @@ class MainActivity : ComponentActivity() { settings.downloadSpeed = it files.setDownloadSpeed(it) }, - volume = effects, - onVolume = { - effects = it - settings.soundVolume = it - audio?.soundVolume = it / 100f - applySceneVolumes() + mix = mixShown, + onMix = { + mixShown = it + applyMix(it) + mixSettings.save(it) }, downloading = downloadJob?.isActive == true, canDownload = catalog != null, @@ -705,10 +724,7 @@ class MainActivity : ComponentActivity() { onBack = { panel = Panel.NONE }) } OverlayFor(problem, { problem = null }) { message -> - WowWindow("Wifecraft", { problem = null }, Modifier.widthIn(max = 500.dp)) { - Text(message, style = frizStyle(14.sp, Color.White)) - RedButton("Close", { problem = null }, Modifier.padding(top = 10.dp)) - } + WifeMessage("Wifecraft", message) { problem = null } } } } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/anim/ClipValidation.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/anim/ClipValidation.kt new file mode 100644 index 00000000..c3f555ad --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/anim/ClipValidation.kt @@ -0,0 +1,60 @@ +package com.logie.wifecraft.anim + +import com.logie.wifecraft.sims.Channel +import kotlin.math.abs +import kotlin.math.acos +import kotlin.math.min +import kotlin.math.sqrt + +/** + * The import's check of a converted clip, before it is offered for the library: a clip that would play broken is skipped + * with a plain reason ([ImportPipeline]: ImportEvent.Skipped) rather than saved. Beyond [ClipInspection]'s (no tracks, + * missing or unsorted keys, values that aren't numbers, rotations that aren't unit, a moving clip with no length): + * a clip that moves none of the body's main bones, one longer than [MAX_SECONDS], keys far past the clip's end, a root + * that jumps further than [MAX_ROOT_STEP] between two keys, and a bone that turns more than [MAX_TURN_DEG] between two + * keys under [FAST_KEYS] seconds apart (a broken curve: the limb would flip or twist in one frame). + */ +object ClipValidation { + const val MAX_SECONDS = 600f + const val MAX_ROOT_STEP = 2.0f + const val MAX_TURN_DEG = 120.0 + const val FAST_KEYS = 0.1f + + /** The body's main bones (WoW-side names): a clip must drive at least one. */ + val BODY = setOf("Root", "Pelvis", "Spine1", "Spine2", "Chest", "Neck1", "Head", "L_Clavicle", "R_Clavicle", "L_UpperArm", + "R_UpperArm", "L_Forearm", "R_Forearm", "L_Thigh", "R_Thigh", "L_Calf", "R_Calf") + + /** Why [a] would play broken (a sentence for the player), or null when it is fine. */ + fun problem(a: Anim): String? { + ClipInspection.inspect(a).takeIf { it.type == ClipType.INVALID }?.let { return it.reason ?: "The clip can't be played." } + if (a.duration > MAX_SECONDS) return "The clip is longer than ten minutes." + if (a.tracks.none { it.bone in BODY }) return "The clip moves none of the body's main bones (only hands, face or helpers)." + val end = a.duration + if (end > 0f && a.tracks.any { it.times.last() > end + 1f }) return "Keyframes run past the clip's end." + for (t in a.tracks) { + if (t.channel == Channel.POSITION) { + if (t.bone != "Root") continue + for (k in 1 until t.times.size) { + val dx = t.values[k * 3] - t.values[k * 3 - 3] + val dy = t.values[k * 3 + 1] - t.values[k * 3 - 2] + val dz = t.values[k * 3 + 2] - t.values[k * 3 - 1] + if (sqrt(dx * dx + dy * dy + dz * dz) > MAX_ROOT_STEP) return "The body jumps away between two keyframes." + } + } else { + for (k in 1 until t.times.size) { + if (t.times[k] - t.times[k - 1] > FAST_KEYS) continue + var dot = 0.0 + for (c in 0 until 4) dot += t.values[(k - 1) * 4 + c].toDouble() * t.values[k * 4 + c] + // the turn between the two keys, the short way (q and -q are the same turn) + val deg = Math.toDegrees(2 * acos(min(1.0, abs(dot)))) + if (deg > MAX_TURN_DEG) return "A bone (${t.bone}) flips between two keyframes; the clip's curves are damaged." + } + } + } + return null + } + + /** A partner animation's [problem]: either clip's, said with its actor. */ + fun problem(p: PairAnim): String? = + problem(p.a)?.let { "Actor A: $it" } ?: problem(p.b)?.let { "Actor B: $it" } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/anim/ImportPipeline.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/anim/ImportPipeline.kt index a2debc3e..35c05424 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/anim/ImportPipeline.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/anim/ImportPipeline.kt @@ -37,7 +37,8 @@ class ImportResult(val anims: List, val pairs: List, val unpaire * A package's clips are first paired ([Pairing]: its tuning, the clip names, the geometry); a pair is converted * together ([Retarget.convertPair]) and reported as [ImportEvent.Paired]; every other clip is converted alone, * those that look like half of a pair also reported as [ImportEvent.Unpaired]. A package of one clip is a single. - * The converted animations are returned unsaved: the review screen renames them and adds them to the [AnimLibrary]. */ + * The converted animations are returned unsaved: the review screen renames them and adds them to the [AnimLibrary]. + * A converted clip or pair that would play broken ([ClipValidation]) is reported as [ImportEvent.Skipped], not returned. */ class ImportPipeline( private val retarget: Retarget, private val tmpDir: File, @@ -214,7 +215,10 @@ class ImportPipeline( onEvent(ImportEvent.Found(label)) try { val p = retargetForClip(f.a).convertPair(f.a, f.b, f.def) - onEvent(ImportEvent.Paired(p.name, p, f.mode)) + // a pair that would play broken is said and left out, never saved (ClipValidation) + val broken = ClipValidation.problem(p) + if (broken != null) onEvent(ImportEvent.Skipped(label, broken)) + else onEvent(ImportEvent.Paired(p.name, p, f.mode)) } catch (e: Exception) { onEvent(ImportEvent.Failed(label, e.message ?: e.javaClass.simpleName)) // a pair that does not convert is still two clips the person can try by hand @@ -245,6 +249,9 @@ class ImportPipeline( try { val anim = retargetForClip(clip).convert(clip) val result = anim.copy(name = anim.name.ifBlank { name }, source = anim.source.ifBlank { clip.sourceKey }) + // a clip that would play broken is said and left out, never saved (ClipValidation) + val broken = ClipValidation.problem(result) + if (broken != null) { onEvent(ImportEvent.Skipped(label, broken)); return } out.add(result) onEvent(ImportEvent.Done(result)) } catch (e: Exception) { diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/Audio.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/Audio.kt index de1715ab..a0fd9587 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/Audio.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/Audio.kt @@ -6,208 +6,314 @@ import android.media.MediaPlayer import android.media.SoundPool import android.os.Handler import android.os.Looper +import android.os.SystemClock import com.logie.wifecraft.data.GameFiles import com.logie.wifecraft.play.Sounds -import org.json.JSONObject +import java.util.concurrent.Executors import kotlin.random.Random /** - * The game's music and sounds (assets/sounds.json, tools/sounds.py), played from the files fetched - * from wago.tools: music crossfades between two players and loops; the city's ambience loops under - * it; effects, voices and the interface's sounds go through a sound pool. Anything not fetched yet - * stays silent. Main thread only. + * The app's soundscape on the phone: a music bed and an ambience bed, each through a [Crossfader] (two MediaPlayers fading + * into one another), the title's music ([title]) and a place's ([place]: ZoneMusic's tracks one after another with a + * short gap, its ambience looped under them), the interface's sounds through a SoundPool ([ui]), the Sound page's mixer + * ([levels]), the beds ducking while someone speaks ([voices]), and silence when the app is paused. The decisions are + * Soundscape.kt's (JVM-tested); this only plays them. + * + * Files are the game's, by id (assets/sounds.json), fetched from wago.tools as they are first needed, off the main thread + * ([GameFiles.fetchNow]); one that can't be fetched leaves its bed silent and is tried again later ([RetryPolicy]): nothing + * here throws. MediaPlayer decodes the game's .mp3 music and .ogg sounds itself. Main thread only. NOT heard on a phone: it + * compiles in CI; no one has listened to it. */ class Audio(context: Context, private val files: GameFiles) : Sounds { - private val music: Map - private val ambiences: Map - private val ui: Map> - private val voices: Map>> - private val effects: Map> + private val book: SoundBook = SoundBook.parse(context.assets.open("sounds.json").bufferedReader().use { it.readText() }) + private val handler = Handler(Looper.getMainLooper()) + private val io = Executors.newSingleThreadExecutor { r -> Thread(r, "audio-fetch").apply { isDaemon = true } } - init { - val o = JSONObject(context.assets.open("sounds.json").bufferedReader().use { it.readText() }) - fun ints(m: JSONObject) = m.keys().asSequence().associateWith { m.getInt(it) } - fun lists(m: JSONObject) = m.keys().asSequence().associateWith { k -> m.getJSONArray(k).let { a -> List(a.length()) { a.getInt(it) } } } - music = ints(o.getJSONObject("music")) - ambiences = ints(o.getJSONObject("ambience")) - ui = lists(o.getJSONObject("ui")) - effects = lists(o.getJSONObject("effects")) - val v = o.getJSONObject("voices") - voices = v.keys().asSequence().associateWith { lists(v.getJSONObject(it)) } - } - - /** 0..1, from the options. */ - var musicVolume = 0.7f - set(value) { field = value; applyVolumes() } - var soundVolume = 0.85f - set(value) { field = value; applyVolumes() } + /** The Sound page's levels (Options): applied at once to everything playing. */ + var levels = MixLevels() + set(value) { field = value; applyVolumes(); if (!value.enabled) pool.autoPause() else if (!paused) pool.autoResume() } - private val handler = Handler(Looper.getMainLooper()) - private val pool = SoundPool.Builder().setMaxStreams(8).setAudioAttributes( - AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build(), - ).build() - private val loaded = mutableMapOf() // file id -> sound pool id, once loaded - private val loading = mutableMapOf() // sound pool id -> file id, while loading - private val playWhenLoaded = mutableSetOf() // sound pool ids asked for before they loaded - - private class Track(val name: String, val player: MediaPlayer, val isAmbience: Boolean = false) { - var level = 0f // its own fade, 0..1 - var target = 0f - var step = 0f // per tick - } - private var current: Track? = null - private val fading = mutableListOf() - private var ambience: Track? = null - private var paused = false - private var wantedMusic = "" + private val ducker = Ducker() - init { - pool.setOnLoadCompleteListener { p, id, status -> - val file = loading.remove(id) ?: return@setOnLoadCompleteListener - if (status != 0) return@setOnLoadCompleteListener - loaded[file] = id - if (playWhenLoaded.remove(id) && !paused) p.play(id, soundVolume, soundVolume, 1, 0, 1f) + /** + * Whether a file not on the phone may be fetched now (the player has gathered the game's files, so has said yes to + * downloading): until then only what is already here plays. Turning it on starts what should already be playing. + */ + var fetchAllowed = false + set(value) { + val was = field + field = value + if (value && !was) { bed?.let { b -> bed = null; ambienceKey = ""; setBed(b, MusicPicker.FADE_MS) }; filesArrived() } } - // The short sounds are loaded ahead, so they play on time. - for (ids in ui.values + effects.values + voices.values.flatMap { it.values }) for (id in ids) load(id) - } - private fun load(file: Int): Int? { - loaded[file]?.let { return it } - loading.entries.firstOrNull { it.value == file }?.let { return it.key } - if (!files.has(file)) return null - val id = pool.load(files.file(file).path, 1) - loading[id] = file - return id - } + // ---- the beds --------------------------------------------------------------------------------------------------- - private fun playShort(file: Int) { - if (paused) return - val id = load(file) ?: return - if (loaded[file] == id) pool.play(id, soundVolume, soundVolume, 1, 0, 1f) else playWhenLoaded += id - } + private val music = Crossfader() + private val ambience = Crossfader() + private val players = HashMap() // deck id -> its player (music and ambience decks: ids never clash, see deckKey) + private var bed: MusicBed? = null + private var ambienceKey = "" + private var token = 0 // a new bed makes the old one's pending work do nothing + private var played = 0 // tracks of this bed so far + private var seed = 0L + private var paused = false + private val attempts = HashMap() - override fun music(name: String, fadeMs: Int) { - wantedMusic = name - if (current?.name == name) return - current?.let { fadeOut(it, fadeMs) } - current = null - val file = music[name] ?: return - val player = start(file, loop = true) ?: return - current = Track(name, player).also { t -> - t.target = 1f - t.step = if (fadeMs <= 0) 1f else TICK_MS.toFloat() / fadeMs - if (fadeMs <= 0) t.level = 1f - } - applyVolumes() - tick() + /** Off the main thread (nothing once released). */ + private fun background(task: () -> Unit) { runCatching { io.execute(task) } } + + private fun deckKey(isAmbience: Boolean, id: Int) = if (isAmbience) -id else id + + /** The title's music (sounds.json's title), the ambience off. */ + fun title() = setBed(MusicPicker.title(book), MusicPicker.TITLE_FADE_MS) + + /** A place's music and ambience (sounds.json's places, by the location's id); silence for a place without sound. */ + fun place(locationId: String, night: Boolean = false) { + val p = book.places[locationId]?.let { MusicPicker.place(it, night) } + if (p == null) silence() else setBed(p, MusicPicker.FADE_MS) } - override fun ambience(name: String) { - val file = ambiences[name] - if (ambience?.name == name) return - ambience?.let { fadeOut(it, 1200) } - ambience = null - if (file == null) return - val player = start(file, loop = true) ?: return - ambience = Track(name, player, isAmbience = true).also { it.target = 1f; it.step = TICK_MS / 1200f } - applyVolumes() + /** Both beds fade out (a screen without music: the creator, the importers). */ + fun silence(fadeMs: Int = MusicPicker.FADE_MS) { + token++; bed = null; ambienceKey = "" + music.stop(fadeMs); ambience.stop(fadeMs) tick() } - override fun effect(name: String) { - effects[name]?.takeIf { it.isNotEmpty() }?.let { playShort(it[Random.nextInt(it.size)]) } + private fun setBed(b: MusicBed, fadeMs: Int) { + if (bed?.key == b.key) return + bed = b + val t = ++token + played = 0 + seed = b.key.hashCode().toLong() * 31 + SystemClock.elapsedRealtime() / 60_000 + // the ambience: the new loop crossfades in, or the old one fades away + val amb = b.ambience.firstOrNull() + val ak = amb?.toString() ?: "" + if (ak != ambienceKey) { + ambienceKey = ak + if (amb == null || !files.has(amb)) ambience.stop(fadeMs) + if (amb != null) ready(amb, t) { startDeck(amb, isAmbience = true, loop = true, fadeMs = fadeMs, t = t) } + } + if (b.tracks.isEmpty()) music.stop(fadeMs) else nextTrack(t, fadeMs) + tick() } - override fun voice(look: String, emote: String) { - voices[look]?.get(emote)?.takeIf { it.isNotEmpty() }?.let { playShort(it[Random.nextInt(it.size)]) } + private fun nextTrack(t: Int, fadeMs: Int) { + val b = bed ?: return + if (t != token) return + val file = (if (b.loop) b.tracks.firstOrNull() else MusicPicker.at(b.tracks, seed, played)) ?: return + // what plays now fades at once when the next file has to be fetched first (no old music carrying on meanwhile) + if (!files.has(file)) music.stop(fadeMs) + ready(file, t) { startDeck(file, isAmbience = false, loop = b.loop, fadeMs = fadeMs, t = t) } } - override fun ui(name: String) { - ui[name]?.firstOrNull()?.let { playShort(it) } + /** [then] on the main thread once [file] is on the phone (fetched now when it isn't); retried later when it can't be had. */ + private fun ready(file: Int, t: Int, then: () -> Unit) { + if (files.has(file)) { then(); return } + if (!fetchAllowed) return + background { + val ok = try { files.fetchNow(file); files.has(file) } catch (e: Exception) { false } + handler.post { + if (t != token) return@post + if (ok) { attempts.remove(file); then() } + else { + // offline, or wago.tools said no: this bed stays quiet and tries again in a while + val n = (attempts[file] ?: 0) + 1 + attempts[file] = n + handler.postDelayed({ if (t == token) ready(file, t, then) }, RetryPolicy.delayMs(n)) + } + } + } } - private fun start(file: Int, loop: Boolean): MediaPlayer? { - if (!files.has(file)) return null - return try { + private fun startDeck(file: Int, isAmbience: Boolean, loop: Boolean, fadeMs: Int, t: Int) { + if (t != token) return + val fader = if (isAmbience) ambience else music + val player = try { MediaPlayer().apply { setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()) setDataSource(files.file(file).path) isLooping = loop setVolume(0f, 0f) - prepare() - if (!paused) start() } - } catch (e: Exception) { - null + } catch (e: Exception) { return } + val deck = fader.play(file, fadeMs) + val key = deckKey(isAmbience, deck.id) + players[key] = player + player.setOnErrorListener { _, _, _ -> + // a file the phone can't decode: dropped quietly (a music bed moves on to its next track) + fader.end(deck.id); players.remove(key)?.let { runCatching { it.release() } } + if (!isAmbience && t == token) handler.postDelayed({ played++; nextTrack(t, MusicPicker.FADE_MS) }, MusicPicker.MIN_GAP_MS) + true + } + player.setOnCompletionListener { + fader.end(deck.id); players.remove(key)?.let { runCatching { it.release() } } + val b = bed + if (!isAmbience && t == token && b != null) { + played++ + handler.postDelayed({ nextTrack(t, MusicPicker.FADE_MS) }, MusicPicker.gapMs(b.gapMs, seed + played)) + } } + player.setOnPreparedListener { p -> + if (players[key] !== p) return@setOnPreparedListener + applyVolumes() + if (!paused) runCatching { p.start() } + tick() + } + runCatching { player.prepareAsync() }.onFailure { fader.end(deck.id); players.remove(key); runCatching { player.release() } } + tick() } - private fun fadeOut(t: Track, ms: Int) { - t.target = 0f - t.step = if (ms <= 0) 1f else TICK_MS.toFloat() / ms - fading += t + // ---- the mixer and its clock ------------------------------------------------------------------------------------ + + /** How many voices are speaking now (SceneAudio.onVoices): the beds dip under them. */ + fun voices(n: Int) { + ducker.setVoices(n) tick() } private var ticking = false + private var last = 0L + private fun tick() { if (ticking) return ticking = true + last = SystemClock.uptimeMillis() handler.post(object : Runnable { override fun run() { - var busy = false - val all = listOfNotNull(current, ambience) + fading - for (t in all) { - if (t.level < t.target) t.level = minOf(t.target, t.level + t.step) - else if (t.level > t.target) t.level = maxOf(t.target, t.level - t.step) - if (t.level != t.target) busy = true - } - for (t in fading.filter { it.level <= 0f }) { - runCatching { t.player.release() } - fading.remove(t) - } + val now = SystemClock.uptimeMillis() + val dt = (now - last).coerceIn(1, 200) + last = now + for (d in music.step(dt)) players.remove(deckKey(false, d.id))?.let { runCatching { it.release() } } + for (d in ambience.step(dt)) players.remove(deckKey(true, d.id))?.let { runCatching { it.release() } } + ducker.step(dt) applyVolumes() - if (busy || fading.isNotEmpty()) handler.postDelayed(this, TICK_MS.toLong()) else ticking = false + if (music.busy || ambience.busy || ducker.moving) handler.postDelayed(this, TICK_MS) else ticking = false } }) } private fun applyVolumes() { - for (t in listOfNotNull(current, ambience) + fading) { - val v = t.level * if (t.isAmbience) soundVolume * AMBIENCE_LEVEL else musicVolume - runCatching { t.player.setVolume(v, v) } + val m = Mixer.gain(levels, Bus.MUSIC, ducker.level) + val a = Mixer.gain(levels, Bus.AMBIENCE, ducker.ambienceLevel) + for (d in music.decks) players[deckKey(false, d.id)]?.let { p -> val v = d.level * m; runCatching { p.setVolume(v, v) } } + for (d in ambience.decks) players[deckKey(true, d.id)]?.let { p -> val v = d.level * a; runCatching { p.setVolume(v, v) } } + } + + // ---- short sounds: the interface, the story's effects and voices -------------------------------------------------- + + private val pool = SoundPool.Builder().setMaxStreams(8).setAudioAttributes( + AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build(), + ).build() + private val loaded = HashMap() // file id -> sound pool id, once loaded + private val loading = HashMap() // sound pool id -> file id, while loading + private val fetching = HashSet() + private val playWhenLoaded = HashMap() // sound pool ids asked for before they loaded + + init { + pool.setOnLoadCompleteListener { p, id, status -> + val file = loading.remove(id) ?: return@setOnLoadCompleteListener + val bus = playWhenLoaded.remove(id) + if (status != 0) return@setOnLoadCompleteListener + loaded[file] = id + if (bus != null && !paused) Mixer.gain(levels, bus).let { v -> if (v > 0f) p.play(id, v, v, 1, 0, 1f) } + } + filesArrived() + } + + private fun load(file: Int): Int? { + loaded[file]?.let { return it } + loading.entries.firstOrNull { it.value == file }?.let { return it.key } + if (!files.has(file)) { + // the interface's sounds are tiny: fetched as they are first wanted (played from the next time) + if (fetchAllowed && fetching.add(file)) background { + val ok = runCatching { files.fetchNow(file) }.isSuccess + handler.post { fetching.remove(file); if (ok) load(file) } + } + return null } + val id = runCatching { pool.load(files.file(file).path, 1) }.getOrNull() ?: return null + loading[id] = file + return id + } + + private fun playShort(file: Int, bus: Bus) { + if (paused) return + val v = Mixer.gain(levels, bus) + if (v <= 0f) return + val id = load(file) ?: return + if (loaded[file] == id) pool.play(id, v, v, 1, 0, 1f) else playWhenLoaded[id] = bus } - /** The app went to the background (or came back). */ + private fun pick(list: List?): Int? = list?.takeIf { it.isNotEmpty() }?.let { it[Random.nextInt(it.size)] } + + override fun ui(name: String) { + val n = UiSounds.resolve(name, book.ui.keys) ?: return + pick(book.ui[n])?.let { playShort(it, Bus.UI) } + } + + override fun effect(name: String) { pick(book.effects[name])?.let { playShort(it, Bus.EFFECTS) } } + + override fun voice(look: String, emote: String) { pick(book.voices[look]?.get(emote))?.let { playShort(it, Bus.DIALOG) } } + + // ---- the story's named music and ambience (play/Sounds) ----------------------------------------------------------- + + override fun music(name: String, fadeMs: Int) { + val file = book.music[name] + if (file == null) { token++; bed = null; music.stop(fadeMs); tick(); return } + val b = MusicBed("story:$name", listOf(file), loop = true) + if (bed?.key == b.key) return + bed = b + val t = ++token + played = 0 + nextTrack(t, fadeMs) + tick() + } + + override fun ambience(name: String) { + val file = book.ambience[name] + val key = file?.toString() ?: "" + if (key == ambienceKey) return + ambienceKey = key + if (file == null) { ambience.stop(1200); tick(); return } + val t = token + ready(file, t) { startDeck(file, isAmbience = true, loop = true, fadeMs = 1200, t = t) } + } + + // ---- the app's life --------------------------------------------------------------------------------------------- + + /** The app went to the background: everything holds, silent. */ fun pause() { paused = true - for (t in listOfNotNull(current, ambience) + fading) runCatching { if (t.player.isPlaying) t.player.pause() } + for (p in players.values) runCatching { if (p.isPlaying) p.pause() } pool.autoPause() } + /** Back: what was playing carries on. */ fun resume() { + if (!paused) return paused = false - for (t in listOfNotNull(current, ambience)) runCatching { t.player.start() } - pool.autoResume() + for (p in players.values) runCatching { p.start() } + if (levels.enabled) pool.autoResume() + tick() } - /** Once the sounds are fetched: start what should already be playing. */ + /** The sound files were gathered: the short sounds loaded ahead, so they play on time. */ fun filesArrived() { - for (ids in ui.values + effects.values + voices.values.flatMap { it.values }) for (id in ids) load(id) - if (current == null && wantedMusic.isNotEmpty()) music(wantedMusic, 1500) + // what is here is loaded; what isn't is fetched when fetching is allowed (load decides) + for (id in book.shortFiles) load(id) } fun release() { + token++ handler.removeCallbacksAndMessages(null) - for (t in listOfNotNull(current, ambience) + fading) runCatching { t.player.release() } - current = null; ambience = null; fading.clear() + for (p in players.values) runCatching { p.release() } + players.clear(); music.clear(); ambience.clear() + io.shutdownNow() pool.release() } private companion object { - const val TICK_MS = 50 - const val AMBIENCE_LEVEL = 0.55f // under the music + const val TICK_MS = 40L } } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/MixSettings.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/MixSettings.kt new file mode 100644 index 00000000..a5363f2c --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/MixSettings.kt @@ -0,0 +1,34 @@ +package com.logie.wifecraft.audio + +import android.content.Context + +/** + * The Sound page's levels kept between runs, in the app's own preferences ("wifecraft", the same file and keys as + * data/Settings: musicVolume, ambienceVolume, soundVolume, voiceVolume), with Master and Enable Sound added here. + */ +class MixSettings(context: Context) { + private val prefs = context.getSharedPreferences("wifecraft", Context.MODE_PRIVATE) + + fun load(): MixLevels { + val sound = prefs.getInt("soundVolume", 85) + return MixLevels( + enabled = prefs.getBoolean("soundEnabled", true), + master = prefs.getInt("masterVolume", 100).coerceIn(0, 100), + music = prefs.getInt("musicVolume", 70).coerceIn(0, 100), + ambience = prefs.getInt("ambienceVolume", sound).coerceIn(0, 100), + effects = sound.coerceIn(0, 100), + dialog = prefs.getInt("voiceVolume", sound).coerceIn(0, 100), + ) + } + + fun save(m: MixLevels) { + prefs.edit() + .putBoolean("soundEnabled", m.enabled) + .putInt("masterVolume", m.master) + .putInt("musicVolume", m.music) + .putInt("ambienceVolume", m.ambience) + .putInt("soundVolume", m.effects) + .putInt("voiceVolume", m.dialog) + .apply() + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/SceneAudio.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/SceneAudio.kt index 1b69db89..4b4f8efc 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/SceneAudio.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/SceneAudio.kt @@ -73,8 +73,21 @@ class SceneAudio(private val context: Context, private val files: GameFiles, pri override fun later(ms: Long, task: () -> Unit) { handler.postDelayed(task, ms) } }, onError = { _error.value = it }, + onVoices = { coreVoices = it; tellVoices() }, ) + /** + * Told on the main thread whenever the number of voices playing changes (the emotes' and the partner sounds'): the + * activity ducks the music under them (Audio.voices). + */ + var onVoices: (Int) -> Unit = {} + private var coreVoices = 0 + private var toldVoices = 0 + private fun tellVoices() { + val n = coreVoices + partnerVoices.size + if (n != toldVoices) { toldVoices = n; onVoices(n) } + } + /** Music, ambience, effects and voices, 0..1 each (the options' sliders; voices default to the sounds' level). */ var volumes: SoundVolumes get() = core.volumes @@ -126,7 +139,7 @@ class SceneAudio(private val context: Context, private val files: GameFiles, pri val loopKey = if (loop && actorKey != null) tag else null val box = arrayOfNulls(1) pool.execute { - val v = PlayerVoice.create(handler, file.path, loop, level, 0) { handler.post { partnerVoices.removeAll { it.second === box[0] } } } + val v = PlayerVoice.create(handler, file.path, loop, level, 0) { handler.post { partnerVoices.removeAll { it.second === box[0] }; tellVoices() } } box[0] = v handler.post { when { @@ -135,6 +148,7 @@ class SceneAudio(private val context: Context, private val files: GameFiles, pri else -> { if (loopKey != null) { partnerVoices.filter { it.first == loopKey }.forEach { it.second.stop(0) }; partnerVoices.removeAll { it.first == loopKey } } partnerVoices.add(loopKey to v) + tellVoices() } } } @@ -147,6 +161,7 @@ class SceneAudio(private val context: Context, private val files: GameFiles, pri partnerGen++ partnerVoices.forEach { it.second.stop(0) } partnerVoices.clear() + tellVoices() } fun release() { diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/SceneAudioCore.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/SceneAudioCore.kt index f4fa448d..b6e69394 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/SceneAudioCore.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/SceneAudioCore.kt @@ -60,6 +60,8 @@ class SceneAudioCore( private val out: SoundOut, private val sched: SoundScheduler, private val onError: (String) -> Unit = {}, + /** How many voices (emotes' voices) are playing, told each time it changes: the music ducks under them (Audio). */ + private val onVoices: (Int) -> Unit = {}, ) { private enum class Channel { MUSIC, AMBIENCE, EFFECT, VOICE } private class Live(val voice: SoundVoice, val channel: Channel, val placement: String?, var ended: Boolean = false) @@ -239,16 +241,24 @@ class SceneAudioCore( private fun start(file: Int, c: Channel, placement: String?, loop: Boolean, fadeMs: Int, done: () -> Unit = {}): Live? { lateinit var l: Live - val v = out.play(file, loop, level(c), fadeMs) { l.ended = true; live.remove(l); done() } ?: return null + val v = out.play(file, loop, level(c), fadeMs) { l.ended = true; live.remove(l); if (c == Channel.VOICE) tellVoices(); done() } ?: return null l = Live(v, c, placement) live += l if (paused) v.pause() + if (c == Channel.VOICE) tellVoices() return l } private fun stopLive(l: Live, fadeMs: Int) { l.ended = true; live.remove(l) l.voice.stop(fadeMs) + if (l.channel == Channel.VOICE) tellVoices() + } + + private var toldVoices = 0 + private fun tellVoices() { + val n = live.count { it.channel == Channel.VOICE } + if (n != toldVoices) { toldVoices = n; onVoices(n) } } /** [then] on the main thread with whether the file is here: fetched first when it isn't (the error is told, once per try). */ diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/Soundscape.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/Soundscape.kt new file mode 100644 index 00000000..7cda882c --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/audio/Soundscape.kt @@ -0,0 +1,311 @@ +package com.logie.wifecraft.audio + +import org.json.JSONObject +import kotlin.math.max +import kotlin.math.min +import kotlin.random.Random + +// The app's soundscape, apart from the phone (pure JVM: unit-tests/.../audio/SoundscapeTest): the Sound page's mixer (Master, +// Music, Ambience, Sound effects, Dialog, as the game's own Sound settings), the music ducking under voices, the two-deck +// crossfade the music and the ambience beds play through, which music plays where (the title's, a place's: ZoneMusic's +// tracks one after another with a short gap), the retry when a file can't be fetched, and assets/sounds.json read. Audio.kt +// plays what these decide. + +/** The Sound page: Enable Sound and five levels, 0 to 100 each (WoW's Master, Music, Ambience, Sound effects, Dialog). */ +data class MixLevels( + val enabled: Boolean = true, + val master: Int = 100, + val music: Int = 70, + val ambience: Int = 60, + val effects: Int = 85, + val dialog: Int = 90, +) + +/** Where a sound goes: the beds (music, ambience), the scene's effects, the people's voices, the interface's clicks. */ +enum class Bus { MUSIC, AMBIENCE, EFFECTS, DIALOG, UI } + +object Mixer { + /** + * A slider's 0..100 as a player's gain: squared, so the slider's middle sounds like the middle (a player's volume is a + * plain amplitude scale; the ear hears it roughly logarithmically). + */ + fun curve(percent: Int): Float = (percent.coerceIn(0, 100) / 100f).let { it * it } + + /** The gain of [bus] under [levels]: Master times the bus (the interface's clicks under Sound effects), times [duck] for the beds. */ + fun gain(levels: MixLevels, bus: Bus, duck: Float = 1f): Float { + if (!levels.enabled) return 0f + val own = when (bus) { + Bus.MUSIC -> levels.music + Bus.AMBIENCE -> levels.ambience + Bus.EFFECTS, Bus.UI -> levels.effects + Bus.DIALOG -> levels.dialog + } + val d = if (bus == Bus.MUSIC || bus == Bus.AMBIENCE) duck.coerceIn(0f, 1f) else 1f + return (curve(levels.master) * curve(own) * d).coerceIn(0f, 1f) + } + + /** + * The scene's sounds' levels (SceneAudio: its ambience is played at ambience x effects) so that each comes out at + * [gain]: the ambience given as its share of the effects'. + */ + fun sceneVolumes(levels: MixLevels): SoundVolumes { + val fx = gain(levels, Bus.EFFECTS) + val amb = gain(levels, Bus.AMBIENCE) + return SoundVolumes( + music = gain(levels, Bus.MUSIC), + ambience = if (fx > 0f) min(1f, amb / fx) else 0f, + effects = fx, + voices = gain(levels, Bus.DIALOG), + ) + } +} + +/** + * The beds dip while someone speaks: [voiceStarted] and [voiceEnded] count the voices (or [setVoices] sets the count), [step] + * moves [level] toward [depth] (a voice) or 1 (none) over [attackMs] down and [releaseMs] back up. The ambience dips half as + * far ([ambienceLevel]). + */ +class Ducker(val depth: Float = 0.45f, val attackMs: Int = 180, val releaseMs: Int = 700) { + var voices = 0 + private set + var level = 1f + private set + + val target: Float get() = if (voices > 0) depth else 1f + val ambienceLevel: Float get() = 1f - (1f - level) * 0.5f + val moving: Boolean get() = level != target + + fun voiceStarted() { voices++ } + fun voiceEnded() { voices = max(0, voices - 1) } + fun setVoices(n: Int) { voices = max(0, n) } + + /** [dtMs] later; true when [level] changed. */ + fun step(dtMs: Long): Boolean { + val t = target + if (level == t) return false + val span = 1f - depth + val ms = if (t < level) attackMs else releaseMs + val delta = if (ms <= 0 || span <= 0f) 1f else span * dtMs / ms + level = if (t < level) max(t, level - delta) else min(t, level + delta) + return true + } +} + +/** + * Two (or more, briefly) decks that fade into one another: [play] fades every deck out and a new one in; [step] moves the + * levels on and gives back the decks that have faded out (to release); [end] drops a deck that finished by itself. The + * player's volume is a deck's [Deck.level] times its bus's gain. Pure: the decks hold an [item] (a file id) and an id. + */ +class Crossfader { + class Deck(val id: Int, val item: T) { + var level = 0f + internal set + var target = 0f + internal set + internal var perMs = 1f + val fadingOut: Boolean get() = target == 0f + } + + private var nextId = 1 + private val list = ArrayList>() + + val decks: List> get() = list + /** The deck fading in or playing (the newest not fading out), if any. */ + val current: Deck? get() = list.lastOrNull { !it.fadingOut } + /** True while any level is still moving. */ + val busy: Boolean get() = list.any { it.level != it.target } + + /** A new deck for [item] faded in over [fadeInMs]; every other deck fades out over [fadeOutMs]. */ + fun play(item: T, fadeInMs: Int, fadeOutMs: Int = fadeInMs): Deck { + for (d in list) fadeTo(d, 0f, fadeOutMs) + val d = Deck(nextId++, item) + list += d + fadeTo(d, 1f, fadeInMs) + return d + } + + /** Every deck faded out over [fadeMs]. */ + fun stop(fadeMs: Int) { for (d in list) fadeTo(d, 0f, fadeMs) } + + /** A deck that ended by itself (its track finished): gone without a fade. */ + fun end(id: Int): Deck? = list.firstOrNull { it.id == id }?.also { list.remove(it) } + + /** Everything gone at once (released by the caller). */ + fun clear(): List> = list.toList().also { list.clear() } + + /** [dtMs] later: the levels moved on; the decks that reached silence on their way out are removed and returned. */ + fun step(dtMs: Long): List> { + for (d in list) { + if (d.level < d.target) d.level = min(d.target, d.level + d.perMs * dtMs) + else if (d.level > d.target) d.level = max(d.target, d.level - d.perMs * dtMs) + } + val gone = list.filter { it.fadingOut && it.level <= 0f } + list.removeAll(gone) + return gone + } + + private fun fadeTo(d: Deck, t: Float, ms: Int) { + d.target = t + if (ms <= 0) { d.level = t; d.perMs = 1f } else d.perMs = 1f / ms + } +} + +/** + * What plays as a bed: [tracks] (file ids) one after another in a shuffled order with a gap of [gapMs] between, or one + * looped ([loop]); [ambience] looped under it (none: empty). [key] tells two beds apart: the same key again changes nothing. + */ +data class MusicBed( + val key: String, + val tracks: List, + val ambience: List = emptyList(), + val gapMs: LongRange = MusicPicker.MIN_GAP_MS..MusicPicker.MIN_GAP_MS, + val loop: Boolean = false, +) + +/** A place's sound as sounds.json's places give it (the tables' ids: AreaTable, WMOAreaTable's ZoneMusic, SoundAmbience). */ +data class PlaceSound( + val id: String, + val areaId: Int, + val zoneMusic: Int, + val music: List, + val ambienceDay: List, + val ambienceNight: List, + /** ZoneMusic's silence between tracks (ms): 3 to 5 minutes in the game, shortened here ([MusicPicker.gap]). */ + val silenceMs: Pair, +) + +object MusicPicker { + /** The gap between two of a place's tracks: the game's minutes of silence would leave a scene quiet too long. */ + const val MIN_GAP_MS = 4_000L + const val MAX_GAP_MS = 18_000L + const val FADE_MS = 2_000 + const val TITLE_FADE_MS = 1_200 + + /** The title's music: one track looped (sounds.json's title). */ + fun title(book: SoundBook): MusicBed = MusicBed("title", book.title, loop = true) + + /** A place's music and ambience, by day or by [night] (the other's when one is empty); null when the place has no sound. */ + fun place(p: PlaceSound, night: Boolean): MusicBed? { + val amb = if (night) p.ambienceNight.ifEmpty { p.ambienceDay } else p.ambienceDay.ifEmpty { p.ambienceNight } + if (p.music.isEmpty() && amb.isEmpty()) return null + return MusicBed("place:${p.id}:${if (night) "night" else "day"}", p.music, amb.take(1), gap(p.silenceMs)) + } + + /** The table's silence cut down to [MIN_GAP_MS]..[MAX_GAP_MS] (kept in order: never a backwards range). */ + fun gap(silence: Pair): LongRange { + val lo = silence.first.toLong().coerceIn(MIN_GAP_MS, MAX_GAP_MS) + val hi = silence.second.toLong().coerceIn(lo, MAX_GAP_MS) + return lo..hi + } + + /** One gap from [range] by [seed]. */ + fun gapMs(range: LongRange, seed: Long): Long = + if (range.last <= range.first) range.first else range.first + Random(seed).nextLong(range.last - range.first + 1) + + /** + * The tracks in play order for round [round] (a fresh shuffle each round, by [seed]); a round never starts with the + * track the last one ended on, so nothing plays twice in a row. + */ + fun order(tracks: List, seed: Long, round: Int): List { + if (tracks.size <= 1) return tracks + var o: MutableList = tracks.toMutableList() + var prev: Int? = null + for (r in 0..maxOf(0, round)) { + o = tracks.shuffled(Random(seed + r)).toMutableList() + if (prev != null && o[0] == prev) { o[0] = o[1]; o[1] = prev } + prev = o.last() + } + return o + } + + /** The track at play position [n] (0, 1, 2...: rounds of [order] one after another). */ + fun at(tracks: List, seed: Long, n: Int): Int? { + if (tracks.isEmpty()) return null + return order(tracks, seed, n / tracks.size)[n % tracks.size] + } +} + +/** How long to wait before fetching a file again after it failed: 5 s, 15 s, 45 s, then every 2 minutes. */ +object RetryPolicy { + fun delayMs(attempt: Int): Long = when { + attempt <= 0 -> 0L + attempt == 1 -> 5_000L + attempt == 2 -> 15_000L + attempt == 3 -> 45_000L + else -> 120_000L + } +} + +/** + * The interface's sounds by the app's names, each a sound kit of the game's (SoundKitConstants.lua, the names Blizzard's + * own interface code plays them by): the files are in sounds.json's ui, from SoundKitEntry (tools/sounds.py). There is no + * hover sound: the game's buttons play none on hover. + */ +object UiSounds { + val KITS: Map> = linkedMapOf( + "open" to ("IG_MAINMENU_OPEN" to 850), + "close" to ("IG_MAINMENU_CLOSE" to 851), + "click" to ("IG_MAINMENU_OPTION" to 852), + "ok" to ("GS_TITLE_OPTION_OK" to 798), + "check_on" to ("IG_MAINMENU_OPTION_CHECKBOX_ON" to 856), + "check_off" to ("IG_MAINMENU_OPTION_CHECKBOX_OFF" to 857), + "tab" to ("IG_CHARACTER_INFO_TAB" to 841), + "page" to ("IG_ABILITY_PAGE_TURN" to 836), + "select" to ("IG_QUEST_LIST_SELECT" to 877), + "create" to ("GS_CHARACTER_SELECTION_CREATE_NEW" to 813), + "begin" to ("GS_CHARACTER_SELECTION_ENTER_WORLD" to 809), + "gossip" to ("IG_QUEST_LIST_OPEN" to 875), + "ending" to ("kit 12891 (achievmentsound1.ogg, the achievement toast)" to 12891), + ) + + /** A name the app may ask for that has no kit falls back to the plain click (an unknown name: nothing). */ + fun resolve(name: String, have: Set): String? = when { + name in have -> name + name == "hover" -> null + name in KITS || name.startsWith("check") -> "click".takeIf { it in have } + else -> null + } +} + +/** assets/sounds.json: the story's named music and ambience, the interface's sounds, the title's music, the places' sound. */ +class SoundBook( + val music: Map, + val ambience: Map, + val ui: Map>, + val effects: Map>, + val voices: Map>>, + val title: List, + val places: Map, +) { + /** Every short sound (loaded into the sound pool ahead). */ + val shortFiles: Set get() = (ui.values.flatten() + effects.values.flatten() + voices.values.flatMap { it.values.flatten() }).toSet() + + companion object { + fun parse(json: String): SoundBook { + val o = JSONObject(json) + fun ints(m: JSONObject?) = m?.keys()?.asSequence()?.associateWith { m.getInt(it) }.orEmpty() + fun list(a: org.json.JSONArray?) = if (a == null) emptyList() else List(a.length()) { a.getInt(it) } + fun lists(m: JSONObject?) = m?.keys()?.asSequence()?.associateWith { k -> list(m.optJSONArray(k)) }.orEmpty() + val v = o.optJSONObject("voices") + val places = LinkedHashMap() + o.optJSONObject("places")?.let { p -> + for (id in p.keys()) { + val e = p.getJSONObject(id) + val s = e.optJSONArray("silenceMs") + places[id] = PlaceSound( + id, e.optInt("area"), e.optInt("zoneMusic"), list(e.optJSONArray("music")), + list(e.optJSONArray("ambienceDay")), list(e.optJSONArray("ambienceNight")), + if (s != null && s.length() >= 2) s.getInt(0) to s.getInt(1) else 0 to 0, + ) + } + } + return SoundBook( + ints(o.optJSONObject("music")), ints(o.optJSONObject("ambience")), lists(o.optJSONObject("ui")), + lists(o.optJSONObject("effects")), + v?.keys()?.asSequence()?.associateWith { lists(v.getJSONObject(it)) }.orEmpty(), + list(o.optJSONObject("title")?.optJSONArray("music")), + places, + ) + } + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/catalog/EmoteCatalog.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/catalog/EmoteCatalog.kt index abbef3af..ed633047 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/catalog/EmoteCatalog.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/catalog/EmoteCatalog.kt @@ -98,23 +98,34 @@ class EmoteCatalog private constructor( for ((anim, n) in m.variations) { if (anim in covered || anim in LAYERS) continue val name = anims[anim] ?: "Anim$anim" - rest += Emote(ANIM_BASE + anim, name, anim, 0, emptyList(), EmoteKind.ANIM, categoryOf(name), false, n, labels[anim] ?: name) + rest += Emote(ANIM_BASE + anim, name, anim, 0, emptyList(), EmoteKind.ANIM, categoryOf(name), EmotePlayability.heldByName(name), + n, labels[anim] ?: name) } rest.sortWith(compareBy({ CATEGORIES.indexOf(it.category) }, { it.label.lowercase() })) out += rest out } + /** + * [forModel] without what can't be played well on its own in a scene ([EmotePlayability.problem]: layers, and + * animations made for a mount, flight, water or mid-air). [includeVoiceOnly]: keep text emotes this model only has a + * voice for (no animation); false for lists of animations (Play animation, the partner fallback). + */ + fun playableForModel(raceId: Int, sex: Sex, includeVoiceOnly: Boolean = true): List = + EmotePlayability.playable(forModel(raceId, sex), includeVoiceOnly) { animName(it) } + companion object { const val NPC_BASE = 10000 const val ANIM_BASE = 100000 const val EMOTES = "Emotes" /** - * Animations that are a layer over another, never played alone: FacePose (808) keys the face only, and played on its - * own leaves the body in the bind pose, arms out (measured on all seven test models). + * Animations that are a layer over another, never listed alone: FacePose (808) keys the face only, HandsClosed (15) the + * hands, Stop (3) the arms, Sheath (89) and HipSheath (90) the arms. Played on its own the engine now poses the rest of + * the body as the idle (M2Model::isLayer), so each would show as standing. Measured on the 50 creator models (Nov + * 2026, engine-test/boneanim_test and the audit in the commit): 808 on all, 15 on 31, 3 on 11, 89 and 90 on one each. */ - val LAYERS = setOf(808) + val LAYERS = setOf(808, 15, 3, 89, 90) /** The categories of [categoryOf], in the order the list shows them. */ val CATEGORIES = listOf(EMOTES, "Dance", "Sit, sleep and kneel", "Work and life", "Combat", "Spells", "Death and injury", @@ -127,7 +138,7 @@ class EmoteCatalog private constructor( val n = name.lowercase() fun any(vararg w: String) = w.any { it in n } return when { - n.startsWith("fly") -> "Flying" + n.startsWith("fly") && "kick" !in n -> "Flying" any("dance") -> "Dance" any("sit", "sleep", "kneel", "lean", "crouch") -> "Sit, sleep and kneel" any("death", "dead", "drown", "knockdown", "wound", "stun", "cower", "rise", "critical") -> "Death and injury" diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/catalog/EmotePlayability.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/catalog/EmotePlayability.kt new file mode 100644 index 00000000..3bcdad49 --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/catalog/EmotePlayability.kt @@ -0,0 +1,58 @@ +package com.logie.wifecraft.catalog + +/** + * Which of a model's emotes and animations play well on their own, standing on a floor (pure; the picker's filter, + * [EmoteCatalog.playableForModel]). The catalog lists every sequence the model has; some need what a scene never gives: + * a mount under the rider (Mount, MountSelf*, CarriageMount, ReclinedMount: the rider sits in the air), flight (Fly, + * Glide, Hover, a Dracthyr's air dashes: flown on the floor), water (Swim*, Submerge, Emerge, Torpedo: lying flat on the + * floor), mid-air (Fall, Jump), something to hang from (WAHang), someone carrying them (Carried2H), and layers + * ([EmoteCatalog.LAYERS]: part of the body only). Those are left out, each with a plain reason ([problem]). + */ +object EmotePlayability { + + /** Why the animation [anim] named [name] (wow.export's name; null: unknown) can't be played alone, or null when it can. */ + fun problem(anim: Int, name: String?): String? { + if (anim < 0) return "No animation (voice only)." + if (anim in EmoteCatalog.LAYERS) return "Moves only part of the body; the game plays it over another animation." + val n = name ?: return null + return when { + "Mount" in n || n == "Carried2H" -> "Needs a mount or someone to carry them." + n == "Fly" || n == "Glide" || n == "DHGlide" || n == "Hover" || n.startsWith("PriHover") || + n.startsWith("DracAir") || n.startsWith("DracFly") || n.startsWith("FlyStand") || n.startsWith("FlyWalk") || + n.startsWith("FlyRun") || n.startsWith("FlyIdle") -> "Made for flying." + n.startsWith("Swim") || n.startsWith("Submerge") || n == "Emerge" || n == "Torpedo" -> "Made for swimming." + n == "Fall" || n == "Jump" -> "Made for mid-air." + n.startsWith("WAHang") -> "Needs something to hang from." + else -> null + } + } + + /** The emote [e]'s [problem] ([animName]: the animation's name by id). A voice-only text emote has none when kept. */ + fun problem(e: Emote, animName: (Int) -> String?): String? = problem(e.anim, if (e.anim >= 0) animName(e.anim) else null) + + /** + * [emotes] without those with a [problem]; [includeVoiceOnly] keeps text emotes with a voice and no animation + * (they still speak). The order is kept. + */ + fun playable(emotes: List, includeVoiceOnly: Boolean = true, animName: (Int) -> String?): List = + emotes.filter { e -> + if (e.anim < 0) includeVoiceOnly && e.soundFiles.isNotEmpty() + else problem(e, animName) == null + } + + /** + * Whether an animation the emote tables don't describe (EmoteKind.ANIM) is held (loops) by default, by its name: states + * and cycles loop (stances, sitting, sleeping, dances, walking, channels, the WA* work loops: played once, a dance stopped + * on its last frame); starts, ends, deaths and single moves play once and hold their last frame. + */ + fun heldByName(name: String): Boolean { + val n = name.lowercase() + if (listOf("start", "end", "down", "up", "precast", "death", "dead", "knockdown").any { n.endsWith(it) }) return false + if ("death" in n || n.startsWith("wadead")) return false + if (n.endsWith("loop") || "dance" in n || "channel" in n || "idle" in n) return true + if (name.startsWith("WA") && name.length > 2 && name[2].isUpperCase()) return !n.startsWith("waemote") + val states = listOf("stand", "ready", "hold", "sit", "sleep", "walk", "run", "sprint", "shuffle", "stealth", "kneel", + "meditate", "cower", "stun", "instocks", "lean", "crouch") + return states.any { n.startsWith(it) || n.startsWith("dh$it") || n.startsWith("monk") && it in n } + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/data/Settings.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/data/Settings.kt index 2eae69e9..be1b01a3 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/data/Settings.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/data/Settings.kt @@ -40,6 +40,10 @@ class Settings(context: Context) { var partnerFrequency: String get() = prefs.getString("partnerFrequency", "SOMETIMES") ?: "SOMETIMES" set(v) = prefs.edit().putString("partnerFrequency", v).apply() + /** How often idle NPCs go and talk to each other (speech bubbles): a ChatterFrequency name (ChatterFrequency.of; Sometimes by default). */ + var chatterFrequency: String + get() = prefs.getString("chatterFrequency", "SOMETIMES") ?: "SOMETIMES" + set(v) = prefs.edit().putString("chatterFrequency", v).apply() /** Files fetched at once by the first launch's gathering: Gentle 24, Normal 48, Fast 96 (the ceiling; it backs off by itself). */ var downloadSpeed: Int get() = prefs.getInt("downloadSpeed", FAST).let { if (it in CHOICES) it else FAST } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/Chatter.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/Chatter.kt new file mode 100644 index 00000000..bfc7a827 --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/Chatter.kt @@ -0,0 +1,443 @@ +package com.logie.wifecraft.simulation + +import kotlin.random.Random + +/** An NPC as the talk knows them: [name] (the first word is used), [race] (ChrRaces id; 0 unknown), [female] (null unknown). */ +data class Speaker(val name: String, val race: Int = 0, val female: Boolean? = null) { + val first: String get() = name.trim().substringBefore(' ').ifEmpty { "friend" } +} + +/** + * The NPCs' small talk: original short lines in a Warcraft voice, put together into conversations ([conversation]: a + * greeting and its answer, two to six exchanges on a topic or two, a farewell and its answer). Lines are templates whose + * slots are filled from the two speakers (names, race, home city, sister or brother) and the scene's [place]; a template + * whose slot is unknown is not used. Seeded: the same [Random] gives the same talk. It remembers what was said lately + * (greetings, exchanges, farewells: [RECENT] of them) and never says one of those again until they fall out, nor stays on + * the last conversation's topic. Pure JVM. + */ +class Chatter(private val speakers: Map, place: String) { + private val place = placeRef(place) + private val recent = ArrayDeque() + private var lastTopic = -1 + + /** What [a] (who began it) and [b] say, in order (ChatLine.speaker 0 is [a]). */ + fun conversation(a: String, b: String, random: Random): List { + val sa = speakers[a] ?: Speaker("friend") + val sb = speakers[b] ?: Speaker("friend") + val who = arrayOf(sa, sb) + val out = ArrayList() + val used = HashSet() + + fun line(role: Int, beats: List, keyPrefix: String): Boolean { + val me = who[role]; val you = who[1 - role] + val options = beats.indices.filter { "$keyPrefix$it" !in recent && fill(beats[it].text, me, you) != null } + .ifEmpty { beats.indices.filter { fill(beats[it].text, me, you) != null } } + if (options.isEmpty()) return false + val i = options[random.nextInt(options.size)] + remember("$keyPrefix$i") + out += ChatLine(role, fill(beats[i].text, me, you)!!, beats[i].gesture) + return true + } + + line(0, GREETINGS, "g") + line(1, ANSWERS, "a") + + val count = EXCHANGES[random.nextInt(EXCHANGES.size)] + var topic = pickTopic(random, -1) + // whoever didn't speak last speaks next: the one who came over brings up the first topic, and so on in turn + var leader = 0 + var said = 0 + var guard = 0 + while (said < count && guard++ < 40) { + if (said > 0 && random.nextFloat() < SWITCH_TOPIC) topic = pickTopic(random, topic) + var exchange = pickExchange(topic, used, random, who, leader, fresh = true) + if (exchange == null) { + // this topic's said lately: another, and only when every one is, something said before + val next = pickTopic(random, topic) + if (next != topic) { topic = next; exchange = pickExchange(topic, used, random, who, leader, fresh = true) } + if (exchange == null) exchange = pickExchange(topic, used, random, who, leader, fresh = false) ?: break + } + used += exchange.key + remember(exchange.key) + var role = leader + for (part in exchange.parts) { + val me = who[role]; val you = who[1 - role] + val fits = part.filter { fill(it.text, me, you) != null } + if (fits.isEmpty()) break + val beat = fits[random.nextInt(fits.size)] + out += ChatLine(role, fill(beat.text, me, you)!!, beat.gesture) + role = 1 - role + } + said++ + leader = 1 - out.last().speaker + } + lastTopic = topic + + val closer = 1 - out.last().speaker + line(closer, FAREWELLS, "f") + line(1 - closer, PARTINGS, "p") + + // the listener nods at the end of some plain statements (never a question, a laugh or a farewell's answer) + for (i in 0 until out.size - 1) { + val l = out[i] + if (l.gesture == Gestures.TALK && out[i + 1].speaker != l.speaker && random.nextFloat() < NOD_CHANCE) out[i] = l.copy(nod = true) + } + return out + } + + /** The player's Say list for [id] (short lines the controlled NPC can say), filled in. */ + fun sayings(id: String): List { + val me = speakers[id] ?: Speaker("friend") + val crowd = Speaker("friends") + return SAYINGS.mapNotNull { fill(it, me, crowd) } + } + + private fun remember(key: String) { + recent.remove(key) + recent.addLast(key) + while (recent.size > RECENT) recent.removeFirst() + } + + private fun pickTopic(random: Random, not: Int): Int { + val options = TOPICS.indices.filter { it != not && it != lastTopic && TOPICS[it].exchanges.any { e -> e.key !in recent } } + .ifEmpty { TOPICS.indices.filter { it != not } } + return if (options.isEmpty()) not else options[random.nextInt(options.size)] + } + + private fun pickExchange(topic: Int, used: Set, random: Random, who: Array, leader: Int, fresh: Boolean): Exchange? { + val pool = TOPICS[topic].exchanges.filter { it.key !in used && (!fresh || it.key !in recent) && fits(it, who, leader) } + return if (pool.isEmpty()) null else pool[random.nextInt(pool.size)] + } + + private fun fits(e: Exchange, who: Array, leader: Int): Boolean { + val first = e.parts.firstOrNull() ?: return false + return first.any { fill(it.text, who[leader], who[1 - leader]) != null } + } + + /** [text] with its slots filled for [me] speaking to [you], or null when a slot can't be. */ + internal fun fill(text: String, me: Speaker, you: Speaker): String? { + if ('{' !in text) return text + val sb = StringBuilder() + var i = 0 + while (i < text.length) { + val c = text[i] + if (c != '{') { sb.append(c); i++; continue } + val end = text.indexOf('}', i) + if (end < 0) return null + val value = when (text.substring(i + 1, end)) { + "me" -> me.first + "you" -> you.first + "place" -> place + "Place" -> place.replaceFirstChar { it.uppercase() } + "myhome" -> Races.home(me.race) + "yourhome" -> Races.home(you.race) + "yourkind" -> Races.plural(you.race) + "kin" -> when (you.female) { true -> "sister"; false -> "brother"; null -> null } + else -> null + } ?: return null + sb.append(value) + i = end + 1 + } + return sb.toString() + } + + internal class Beat(val gesture: Int, val text: String) + /** One exchange: [parts] spoken in turn, the first by its leader; each part is a choice of lines. */ + internal class Exchange(val key: String, val parts: List>) + internal class Topic(val name: String, val exchanges: List) + + companion object { + /** Keys remembered: none of them is said again until it falls out. */ + const val RECENT = 24 + const val SWITCH_TOPIC = 0.3f + const val NOD_CHANCE = 0.45f + /** Exchanges in a conversation (two to six, the shorter likelier). */ + private val EXCHANGES = intArrayOf(2, 2, 3, 3, 3, 4, 4, 5, 6) + + /** "the Stormwind Embassy", "Dalaran's streets", "the plaza below...": a place's name as said in a sentence. */ + fun placeRef(name: String): String { + val n = name.trim() + if (n.isEmpty()) return "this place" + val firstWord = n.substringBefore(' ') + return when { + firstWord == "The" || firstWord == "A" || firstWord == "An" -> firstWord.lowercase() + n.substring(firstWord.length) + firstWord.endsWith("'") || firstWord.endsWith("'s") || firstWord.endsWith("’s") -> n + else -> "the $n" + } + } + + private fun t(text: String) = Beat(Gestures.TALK, text) + private fun q(text: String) = Beat(Gestures.QUESTION, text) + private fun x(text: String) = Beat(Gestures.EXCLAIM, text) + private fun l(text: String) = Beat(Gestures.LAUGH, text) + private fun w(text: String) = Beat(Gestures.WAVE, text) + private fun ex(key: String, vararg parts: List) = Exchange(key, parts.toList()) + + internal val GREETINGS = listOf( + w("{you}! There you are."), + w("Well, if it isn't {you}."), + t("Evening, {you}. Have you a moment?"), + w("{you}, over here!"), + t("Ah, {you}. Just the face I hoped to see."), + q("Mind if I join you, {you}?"), + t("{you}, you look like you've been on your feet all day."), + w("Hail, {kin}."), + t("There's a familiar face. How are you keeping, {you}?"), + x("{you}! I've been looking all over for you."), + ) + internal val ANSWERS = listOf( + t("{you}! Good to see you."), + w("{you}! Come, come."), + t("For you? Always."), + t("Barely standing, {you}. But standing."), + l("Ha! I was wondering when you'd turn up."), + t("{you}. I was just thinking about you."), + q("Oh? What brings you over?"), + t("Can't complain. Well, I can. I won't."), + w("Hail, {kin}. Pull up a bit of wall."), + ) + internal val FAREWELLS = listOf( + t("Well, I'd best be off."), + w("Take care of yourself, {you}."), + t("I've kept you long enough."), + t("Back to it, I suppose."), + w("Until next time, {you}."), + x("Is that the bell? I'm late!"), + t("I should let you get on."), + ) + internal val PARTINGS = listOf( + w("Safe roads, {you}."), + w("And you. Don't be a stranger."), + t("Never too long. Go on, then."), + l("Back to it. Same time tomorrow?"), + w("Until then."), + l("You're always late. Go!"), + t("Mind how you go, {kin}."), + ) + + internal val TOPICS = listOf( + Topic("weather", listOf( + ex("weather.wind", + listOf(q("Did you feel that wind this morning?")), + listOf(t("Cut right through my cloak. Spring, they call it."), l("I stopped feeling my ears by noon."))), + ex("weather.rain", + listOf(t("The rain's finally let up.")), + listOf(t("For an hour, maybe. Look at those clouds."), t("Good. The gardens needed it."))), + ex("weather.storm", + listOf(q("Think it'll storm tonight?")), + listOf(t("The old sailors by the docks swear it will."), t("My knee says yes. My knee is rarely wrong."))), + ex("weather.sun", + listOf(x("Sun's out! Someone mark the calendar.")), + listOf(l("Don't say it so loud. It'll hear you."), t("Enjoy it while it lasts. It never does."))), + ex("weather.fog", + listOf(t("The fog's thick enough to lose a gryphon in.")), + listOf(t("Someone did, last week. Took two days to find her.")), + listOf(l("Was she lost, or just hiding from her rider?"))), + )), + Topic("work", listOf( + ex("work.how", + listOf(q("How's the work treating you?")), + listOf(t("Long hours, short pay. The usual."), t("Better, now the new quartermaster has the ledgers in order."), + t("Don't ask. Please. Don't ask."))), + ex("work.letter", + listOf(t("I've been copying the same letter all morning.")), + listOf(q("The same letter? Whatever for?")), + listOf(t("Someone keeps spilling ink on the last page. I suspect it's me."))), + ex("work.watch", + listOf(t("They've put me on the night watch again.")), + listOf(t("Bring a flask. And a second cloak."), q("Again? Who did you upset this time?"))), + ex("work.report", + listOf(x("I finished my report at last!")), + listOf(l("Then the next one's already on your desk, I'd wager."), t("Well done. Now nobody will read it."))), + ex("work.merchant", + listOf(q("Still working for that dwarven merchant?")), + listOf(t("Still. He pays in coin and complaints, in equal measure."))), + ex("work.boots", + listOf(t("I've walked this hall so often I could do it asleep.")), + listOf(l("I think you have, once or twice."))), + )), + Topic("tavern", listOf( + ex("tavern.drink", + listOf(q("Fancy a drink once the bells ring?")), + listOf(t("Only if you're buying."), x("I thought you'd never ask."), t("Just the one. I mean it this time."))), + ex("tavern.ale", + listOf(t("The innkeeper's watered the ale again.")), + listOf(l("He swears he hasn't. The ale disagrees."), t("Then we drink twice as much. Simple."))), + ex("tavern.bard", + listOf(q("Did you hear the bard last night?")), + listOf(l("Hear him? Half the district heard him."), t("I've heard worse. Not often, but I have."))), + ex("tavern.arm", + listOf(t("Someone challenged a tauren to an arm-wrestle at the inn last night.")), + listOf(q("Let me guess how that ended.")), + listOf(l("With a broken table and a round on the house."))), + ex("tavern.cards", + listOf(q("Are you still owed for that card game?")), + listOf(t("Six silver and an apology. I'll settle for the silver."))), + )), + Topic("embassy", listOf( + ex("embassy.busy", + listOf(t("Busy day at {place}.")), + listOf(t("Every envoy in the kingdom wants a signature before supper."), t("Busy? I've seen quieter battlefields."))), + ex("embassy.word", + listOf(q("Any word from upstairs?")), + listOf(t("Only that we're to keep our voices down and our boots clean."), t("Still in talks. Still talking. Always talking."))), + ex("embassy.peace", + listOf(t("Strange times, when old enemies share a hallway.")), + listOf(t("Stranger still that nobody's drawn steel yet."), t("Peace suits us all. Mostly."))), + ex("embassy.archive", + listOf(q("Have you been up to the archives yet?")), + listOf(t("Twice. I still can't find the door I came in by."))), + ex("embassy.seal", + listOf(t("Someone's misplaced the wax seal again.")), + listOf(l("Check the steward's pockets. It's always the steward's pockets."))), + )), + Topic("home", listOf( + ex("home.miss", + listOf(q("Do you miss {yourhome}?")), + listOf(t("Every morning. Then I remember the stairs."), t("Some days. The food, mostly."))), + ex("home.letter", + listOf(t("I've a letter from {myhome}. My sister's getting married.")), + listOf(x("Married! Give her my best."), q("To whom? Not that fisherman?"))), + ex("home.kind", + listOf(q("Is it true what they say about {yourkind}?")), + listOf(q("Depends. What do they say?")), + listOf(l("That you never lose an argument."), t("That you cook better than anyone."))), + ex("home.canals", + listOf(t("They say the canals in Stormwind froze over this winter.")), + listOf(t("Children skating all the way to the cathedral, I heard."))), + ex("home.visit", + listOf(q("Will you go back to {myhome} when this is done?")), + listOf(t("If there's still a bed there for me."))), + )), + Topic("gossip", listOf( + ex("gossip.captain", + listOf(t("You didn't hear this from me, but the captain's courting someone.")), + listOf(q("The captain? Who'd have him?")), + listOf(l("Light help them both."))), + ex("gossip.saddle", + listOf(q("Did you hear about the stable hand and the missing saddle?")), + listOf(t("Heard it three ways already. Each one worse."))), + ex("gossip.sheep", + listOf(t("Word is a mage turned his apprentice into a sheep. Again.")), + listOf(l("Third time this month. The poor lad bleats in his sleep."))), + ex("gossip.flowers", + listOf(t("Someone's been leaving flowers on the steps every morning.")), + listOf(q("Flowers? For whom?")), + listOf(t("That's the mystery, isn't it."))), + ex("gossip.cook", + listOf(t("The cook and the quartermaster aren't speaking.")), + listOf(q("Over what?")), + listOf(l("A turnip. Don't ask me which one."))), + )), + Topic("jokes", listOf( + ex("jokes.gnome", + listOf(q("How many gnomes does it take to light a lamp?")), + listOf(q("How many?")), + listOf(l("Six. One to light it, five to improve it until it explodes."))), + ex("jokes.dwarf", + listOf(t("A dwarf walks into a tavern...")), + listOf(q("And?")), + listOf(l("And walks out three days later, singing."))), + ex("jokes.kobold", + listOf(q("What's the difference between a kobold and a candle?")), + listOf(q("Go on.")), + listOf(l("One of them knows where it's going."))), + ex("jokes.murloc", + listOf(q("Why don't murlocs keep secrets?")), + listOf(q("Why?")), + listOf(l("Everyone can hear them coming."))), + ex("jokes.ogre", + listOf(t("I tried to teach an ogre to count.")), + listOf(q("How far did he get?")), + listOf(l("Two. Then he ate the abacus."))), + )), + Topic("food", listOf( + ex("food.bread", + listOf(q("Have you tried the new baker's bread?")), + listOf(t("Tried it. Nearly lost a tooth on it."), t("Every morning. I'm not proud."))), + ex("food.stew", + listOf(t("I'd trade my boots for a proper stew right now.")), + listOf(l("You'd walk home barefoot, then.")), + listOf(t("Worth it."))), + ex("food.pie", + listOf(t("There's a pie cart by the gate today.")), + listOf(x("Then why are we still standing here?"))), + ex("food.cheese", + listOf(q("Who left the cheese on the windowsill?")), + listOf(t("Not me. Though I did have a look at it."))), + )), + Topic("road", listOf( + ex("road.out", + listOf(q("Still thinking of heading out on the road?")), + listOf(t("As soon as the passes clear."), t("Thinking, yes. Doing, not yet."))), + ex("road.patrol", + listOf(t("A patrol came in this morning, mud to the eyebrows.")), + listOf(q("Murlocs?")), + listOf(t("Worse. Swamp."))), + ex("road.dragon", + listOf(t("My cousin swears she saw a dragon over the hills.")), + listOf(l("Your cousin swears she saw a lot of things."))), + ex("road.map", + listOf(t("I bought a map off a goblin yesterday.")), + listOf(q("Does it show anything real?")), + listOf(t("The price, at least. That was very real."))), + )), + Topic("magic", listOf( + ex("magic.tea", + listOf(t("I tried a cantrip to warm my tea this morning.")), + listOf(q("And?")), + listOf(l("Now I need a new cup. And a new table."))), + ex("magic.portal", + listOf(q("Ever taken a portal on a full stomach?")), + listOf(t("Once. Never again."))), + ex("magic.book", + listOf(t("The book I borrowed keeps whispering at night.")), + listOf(t("Return it, then. Quickly."), l("Mine only hums. You got the better one."))), + )), + ) + + /** What the controlled NPC can say (the cast bar's Say). */ + internal val SAYINGS = listOf( + "Hello there!", + "Good to see you all.", + "Lovely weather today.", + "Anyone for a drink?", + "I could use a rest.", + "Busy day at {place}.", + "Has anyone seen my book?", + "Ha! That's a good one.", + "Watch your step out there.", + "Not now, I'm busy.", + "Farewell, friends.", + ) + } +} + +/** The playable races as small talk names them (ChrRaces ids): a plural and a home. Unknown: null. */ +object Races { + private class Race(val plural: String, val home: String) + private val BY_ID = mapOf( + 1 to Race("humans", "Stormwind"), 2 to Race("orcs", "Orgrimmar"), 3 to Race("dwarves", "Ironforge"), + 4 to Race("night elves", "Darnassus"), 5 to Race("the Forsaken", "the Undercity"), 6 to Race("tauren", "Thunder Bluff"), + 7 to Race("gnomes", "Gnomeregan"), 8 to Race("trolls", "the Echo Isles"), 9 to Race("goblins", "Bilgewater Harbor"), + 10 to Race("blood elves", "Silvermoon"), 11 to Race("draenei", "the Exodar"), 22 to Race("worgen", "Gilneas"), + 24 to Race("pandaren", "the Wandering Isle"), 25 to Race("pandaren", "the Wandering Isle"), 26 to Race("pandaren", "the Wandering Isle"), + 27 to Race("nightborne", "Suramar"), 28 to Race("Highmountain tauren", "Highmountain"), 29 to Race("void elves", "Telogrus"), + 30 to Race("Lightforged draenei", "the Vindicaar"), 31 to Race("Zandalari", "Zuldazar"), 32 to Race("Kul Tirans", "Boralus"), + 34 to Race("Dark Iron dwarves", "Shadowforge City"), 35 to Race("vulpera", "Vol'dun"), 36 to Race("Mag'har", "Nagrand"), + 37 to Race("mechagnomes", "Mechagon"), 52 to Race("dracthyr", "the Forbidden Reach"), 70 to Race("dracthyr", "the Forbidden Reach"), + 84 to Race("earthen", "Dornogal"), 85 to Race("earthen", "Dornogal"), + ) + + fun plural(race: Int): String? = BY_ID[race]?.plural + fun home(race: Int): String? = BY_ID[race]?.home + + /** About where a race's head is above its feet, standing (yards): the speech bubble's anchor. */ + fun headHeight(race: Int): Float = when (race) { + 7, 9, 35, 37 -> 1.15f // gnomes, goblins, vulpera, mechagnomes + 3, 34, 84, 85 -> 1.5f // dwarves, Dark Irons, earthen + 6, 28, 11, 30, 32, 31, 36 -> 2.55f // tauren, draenei, Kul Tirans, Zandalari, Mag'har + 22, 24, 25, 26, 2 -> 2.25f // worgen, pandaren, orcs + else -> 2.05f + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/Conversation.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/Conversation.kt new file mode 100644 index 00000000..0500b9c6 --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/Conversation.kt @@ -0,0 +1,115 @@ +package com.logie.wifecraft.simulation + +/** + * NPCs talking to each other: one line of a conversation ([ChatLine]), a conversation's clock ([Conversation]: which line + * is spoken now, the speaker's gesture and the listener's), how often idle NPCs start one ([ChatterFrequency]) and the + * game animations they gesture with ([Gestures]). The lines themselves come from [Chatter]. Pure JVM. + */ + +/** Line [text] spoken by [speaker] (0: the one who began the conversation, 1: the other), with [gesture] (a game + * animation, [Gestures]) at its start; [nod]: the listener nods as it ends. */ +data class ChatLine(val speaker: Int, val text: String, val gesture: Int, val nod: Boolean = false) + +/** Off, Sometimes, Often: the chance an idle NPC's decision is to go and talk to another (the scene setup's Chatter row). */ +enum class ChatterFrequency(val label: String, val chance: Float) { + OFF("Off", 0f), + SOMETIMES("Sometimes", 0.3f), + OFTEN("Often", 0.65f); + + companion object { + fun of(name: String?): ChatterFrequency = entries.firstOrNull { it.name == name } ?: SOMETIMES + } +} + +/** The game animations (AnimationData ids, data/Emotes) a talker uses; every look fetches them. */ +object Gestures { + const val STAND = 0 + const val TALK = 60 + const val EXCLAIM = 64 + const val QUESTION = 65 + const val WAVE = 67 + const val LAUGH = 70 + const val YES = 185 + + /** The gesture a free line suggests (the player's Say): a question, a laugh, an exclamation, else talking. */ + fun of(text: String): Int { + val t = text.trim() + return when { + t.startsWith("Ha") && (t.startsWith("Ha!") || t.startsWith("Ha,") || t.startsWith("Haha")) -> LAUGH + t.endsWith("?") -> QUESTION + t.endsWith("!") -> EXCLAIM + else -> TALK + } + } +} + +/** How long a line stays up to be read: longer lines longer, between [MIN_READ] and [MAX_READ] seconds. */ +object Reading { + const val MIN_READ = 2.4f + const val MAX_READ = 7.5f + fun seconds(text: String): Float = (1.3f + text.length * 0.06f).coerceIn(MIN_READ, MAX_READ) +} + +/** + * One conversation's clock: [start] begins its first line; [advance] moves it on (each line is up for its reading time, + * then a short pause with nobody speaking); [done] after the last. [gesture] says what each side plays now: the speaker its + * line's gesture for the first moments, then talking; the listener standing, nodding at the end of a line marked so. + */ +class Conversation(val lines: List) { + /** The line being spoken or just spoken (-1: not started). */ + var index = -1 + private set + /** Seconds into the line ([speaking]) or into the pause after it. */ + var clock = 0f + private set + var speaking = false + private set + val started: Boolean get() = index >= 0 + val done: Boolean get() = index >= lines.size + + /** The line up now, or null (a pause, before the start, after the end). */ + val line: ChatLine? get() = if (speaking) lines.getOrNull(index) else null + + /** Begins the first line: its index (0), or -1 when there are no lines. */ + fun start(): Int { + index = 0; clock = 0f + speaking = lines.isNotEmpty() + return if (speaking) 0 else -1 + } + + /** The clock moves [dt] seconds: the index of a line that began now, else -1. */ + fun advance(dt: Float): Int { + if (!started || done) return -1 + clock += dt + if (speaking) { + val length = Reading.seconds(lines[index].text) + if (clock >= length) { clock -= length; speaking = false } + } + if (!speaking && clock >= PAUSE) { + clock = 0f + index++ + if (done) return -1 + speaking = true + return index + } + return -1 + } + + /** The game animation side [role] (0 or 1) plays now, or -1 (the conversation is not running). */ + fun gesture(role: Int): Int { + if (!started || done) return -1 + val l = line ?: return Gestures.STAND + if (l.speaker == role) return if (clock < GESTURE_SECONDS) l.gesture else Gestures.TALK + val length = Reading.seconds(l.text) + return if (l.nod && clock >= length - NOD_SECONDS) Gestures.YES else Gestures.STAND + } + + companion object { + /** Seconds between lines, nobody speaking. */ + const val PAUSE = 0.55f + /** A line's own gesture (a wave, a laugh) plays this long, then the speaker talks. */ + const val GESTURE_SECONDS = 2.2f + /** The listener nods for the last this-many seconds of a line marked [ChatLine.nod]. */ + const val NOD_SECONDS = 1.4f + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/LiveScene.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/LiveScene.kt index ef92dc79..6f3e2951 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/LiveScene.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/LiveScene.kt @@ -23,7 +23,9 @@ data class SceneSnapshot( ) { /** [partner]: the other NPC of a two-person animation, else null; [queued] orders waiting; [repeating] one repeating. */ data class PersonView(val id: String, val activity: Activity, val directed: Boolean, - val queued: Int = 0, val repeating: Boolean = false, val partner: String? = null) + val queued: Int = 0, val repeating: Boolean = false, val partner: String? = null, + /** The other NPC of a conversation, else null. */ + val talkingWith: String? = null) /** Whether [id] may use [item] now. */ fun available(item: SceneObject, id: String): Boolean = item in usable && holders[item].let { it == null || it == id } @@ -51,6 +53,9 @@ class LiveScene( pairs: List = emptyList(), emotes: ModelEmotes = ModelEmotes.STANDARD, partnerChance: Float = PartnerFrequency.SOMETIMES.chance, + /** The NPCs' small talk: what they say ([Chatter]; null: no words) and how often they go and talk (0: never). */ + chatter: Chatter? = null, + chatterChance: Float = 0f, ) { /** Where the frame goes (the 3D view, or a test's recorder). GL thread. */ interface Sink { @@ -66,6 +71,13 @@ class LiveScene( fun playback(index: Int, clip: ClipPlayback?) {} /** A performance's sound event [name] for person [index] is due (its time on the performance's clock passed). */ fun sound(index: Int, name: String) {} + /** Person [index] says [text] now (a speech bubble; [id] new for every line), or stops ([text] null, [id] 0). */ + fun speech(index: Int, text: String?, id: Long) {} + /** + * Person [index]'s game animation while talking changes this frame: a gesture, a nod or standing between lines, or + * (the talk over) back to their activity's own [animation]. Called after [activity] in the same frame. + */ + fun gesture(index: Int, animation: Int) {} } companion object { @@ -78,7 +90,8 @@ class LiveScene( } private val simulation = SceneSimulation(ids, objects, random, durations, initiallyReady = false, wanderOnly = wanderOnly, - route = route, partnerChance = partnerChance, pairs = pairs, emotes = emotes) + route = route, partnerChance = partnerChance, pairs = pairs, emotes = emotes, + chatterChance = chatterChance, chatter = chatter) /** The frame's sink while [frame] runs (the simulation's sound events go to it). */ private var frameSink: Sink? = null val clock = FixedStep() @@ -110,6 +123,8 @@ class LiveScene( private val shownFacing = FloatArray(n) private val lastActivity = arrayOfNulls(n) private val lastPlayback = arrayOfNulls(n) + private val lastSpeech = LongArray(n) + private val lastGesture = IntArray(n) { -1 } private var lastPairStarts = 0 private val cosR = cos(rotation) private val sinR = sin(rotation) @@ -131,7 +146,7 @@ class LiveScene( /** The menus' view now (allocates: on change only). */ fun snapshot(): SceneSnapshot { - val people = simulation.people().map { SceneSnapshot.PersonView(it.id, it.activity, it.directed, it.queued, it.repeating, it.partner) } + val people = simulation.people().map { SceneSnapshot.PersonView(it.id, it.activity, it.directed, it.queued, it.repeating, it.partner, it.talkingWith) } val holders = HashMap() val usable = HashSet() for (item in simulation.objects) { @@ -177,14 +192,30 @@ class LiveScene( val z = if (pose.playback != null) pose.z else prevZ[i] + (curZ[i] - prevZ[i]) * a val onFurniture = pose.furniture != null && (pose.activity == Activity.SIT || pose.activity == Activity.REST) shownFacing[i] = if (onFurniture || pose.playback != null) pose.facing else turnToward(shownFacing[i], pose.facing, turn) + var activityChanged = false if (running && lastActivity[i] != pose.activity) { lastActivity[i] = pose.activity + activityChanged = true sink.activity(i, pose.activity) } if (running && lastPlayback[i] != pose.playback) { lastPlayback[i] = pose.playback sink.playback(i, pose.playback) } + if (running) { + // the talking gesture over the activity's animation; when it ends, the activity's own again + val g = pose.gesture + if (g != lastGesture[i] || (activityChanged && g >= 0)) { + val was = lastGesture[i] + lastGesture[i] = g + if (g >= 0) sink.gesture(i, g) else if (was >= 0 && !activityChanged) sink.gesture(i, pose.activity.animation) + } + val said = if (pose.speech != null) pose.speechId else 0L + if (said != lastSpeech[i]) { + lastSpeech[i] = said + sink.speech(i, pose.speech, said) + } + } val facing = shownFacing[i] + rotation if (onFurniture) { sink.place(i, stageX(pose.ex, pose.ey), stageY(pose.ex, pose.ey), oz + pose.ez, facing, pose.furniture, diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SceneControl.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SceneControl.kt new file mode 100644 index 00000000..87eed235 --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SceneControl.kt @@ -0,0 +1,34 @@ +package com.logie.wifecraft.simulation + +/** + * Who the player controls in the live scene and who that NPC's partner is (the partner animations play with them). Taps + * on NPCs in the 3D view: with nobody controlled, a tap takes control of that NPC; with one controlled, a tap on another + * makes it the partner (a tap on the partner again clears it; a tap on the controlled one changes nothing). The cast bar + * switches who is controlled (its tab again lets go). A new controlled NPC starts with no partner. Pure: the screen keeps + * one in its state. + */ +data class SceneControl(val selected: String? = null, val partner: String? = null) { + /** An NPC tapped in the 3D view. */ + fun tapNpc(id: String): SceneControl = when { + selected == null -> SceneControl(id, null) + id == selected -> this + id == partner -> copy(partner = null) + else -> copy(partner = id) + } + + /** An NPC's tab in the cast bar: control it, or let it go when it is the one controlled. */ + fun tapCast(id: String): SceneControl = if (id == selected) SceneControl() else SceneControl(id, null) + + /** The partner chip's clear button. */ + fun clearPartner(): SceneControl = copy(partner = null) + + /** Nobody controlled (Back, a tap on empty space with the room camera). */ + fun release(): SceneControl = SceneControl() + + /** The cast changed: anyone no longer in [ids] is dropped. */ + fun keep(ids: Collection): SceneControl = when { + selected != null && selected !in ids -> SceneControl() + partner != null && partner !in ids -> copy(partner = null) + else -> this + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SceneSimulation.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SceneSimulation.kt index 3e056eae..3d71e4ad 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SceneSimulation.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SceneSimulation.kt @@ -76,6 +76,11 @@ class Pose { var furniture: SceneObject? = null var playback: ClipPlayback? = null var ex = 0f; var ey = 0f; var ez = 0f + /** The line said now (a speech bubble), or null; [speechId] is new for every line said. */ + var speech: String? = null + var speechId = 0L + /** A game animation played over the activity's while talking (a gesture, a nod, standing between lines), or -1. */ + var gesture = -1 } /** What a person's partner animation is, for the menus and the tests ([SceneSimulation.partnerOf]). [stage] is APPROACH @@ -99,6 +104,10 @@ class SceneSimulation( var pairs: List = emptyList(), /** Which game animations each NPC's model has (the fallback's emotes are picked from both models'). */ var emotes: ModelEmotes = ModelEmotes.STANDARD, + /** The chance an idle NPC's decision is to go and talk with another (0: never; [ChatterFrequency]). */ + var chatterChance: Float = 0f, + /** What NPCs say to each other (null: they chat without words, as before). */ + var chatter: Chatter? = null, ) { data class Person( val id: String, val position: Vec3, val facing: Float, val activity: Activity, val directed: Boolean, @@ -106,6 +115,8 @@ class SceneSimulation( val queued: Int = 0, val repeating: Boolean = false, /** The other NPC of a two-person animation (walking to their places or playing), else null. */ val partner: String? = null, + /** The other NPC of a conversation (walking to it or talking), else null. */ + val talkingWith: String? = null, ) /** A performance's sound event is due: actor [index] (the cast's order), sound [name]. Called inside [tick]. */ @@ -184,8 +195,24 @@ class SceneSimulation( var directed = false /** Seconds before this person may start another partner animation by themselves. */ var cooldown = 0f + /** The conversation this person is in (walking to it, or talking), else null. */ + var talk: Talk? = null + /** Seconds before this person may start or be drawn into another conversation by themselves. */ + var chatCooldown = 0f + /** The last line this person said, its serial, until when it is up, and until when its talking gesture plays. */ + var spoken: String? = null + var spokenId = 0L + var spokenUntil = 0f + var sayGestureUntil = 0f } + /** Two people talking: [a] went to [b]; [conversation] is its lines' clock (started when [a] arrives). */ + private class Talk(val a: Actor, val b: Actor, val conversation: Conversation, val directed: Boolean) + + /** Seconds the simulation has run (the speech bubbles' clock). */ + private var time = 0f + private var speechSerial = 0L + private val actors = actorIds.distinct().mapIndexed { i, id -> Actor(id, i, Vec3((i % 3 - 1) * 1.2f, -0.6f + (i / 3) * 1.45f, 0f), -1.4f, 0.6f + i * 0.45f) }.associateBy { it.id } @@ -213,6 +240,41 @@ class SceneSimulation( out.furniture = item val entry = item?.let { spots[it]?.entry } if (entry != null) { out.ex = entry.x; out.ey = entry.y; out.ez = entry.z } else { out.ex = a.x; out.ey = a.y; out.ez = a.z } + out.speech = a.spoken?.takeIf { time < a.spokenUntil } + out.speechId = a.spokenId + out.gesture = gestureOf(a) + } + + private fun gestureOf(a: Actor): Int { + val talk = a.talk + if (talk != null) return if (a.phase == Phase.ACTING) talk.conversation.gesture(if (talk.a === a) 0 else 1) else -1 + val free = a.phase != Phase.MOVING && a.performance == null && a.target == null + return if (a.spoken != null && time < a.sayGestureUntil && free) Gestures.TALK else -1 + } + + /** What [id] is saying now (tests), or null. */ + fun speech(id: String): String? = actors[id]?.let { a -> a.spoken?.takeIf { time < a.spokenUntil } } + + /** Whether [id] is in a conversation (walking to it or talking). */ + fun talking(id: String): Boolean = actors[id]?.talk != null + + /** The other of [id]'s conversation, or null. */ + fun talkingWith(id: String): String? = actors[id]?.talk?.let { if (it.a.id == id) it.b.id else it.a.id } + + /** + * The player's Say: [id] says [text] in a speech bubble (up for its reading time), talking as it does when standing + * free. False: no such person or nothing to say. + */ + fun say(id: String, text: String): Boolean { + val actor = actors[id] ?: return false + val line = text.trim() + if (line.isEmpty()) return false + val seconds = Reading.seconds(line) + actor.spoken = line + actor.spokenId = ++speechSerial + actor.spokenUntil = time + seconds + actor.sayGestureUntil = time + minOf(seconds, Conversation.GESTURE_SECONDS + 0.8f) + return true } /** Whether [item]'s spot has been measured (it can be used). */ @@ -225,7 +287,8 @@ class SceneSimulation( val item = actor.target.takeIf { actor.phase == Phase.ACTING } Person(actor.id, actor.position, actor.facing, if (actor.phase == Phase.MOVING) Activity.WALK else actor.activity, actor.directed, item, item?.let { spots[it]?.entry } ?: actor.position, - actor.queue.size, actor.performance?.repeat == true, partnerOf(actor)?.id) + actor.queue.size, actor.performance?.repeat == true, partnerOf(actor)?.id, + actor.talk?.let { if (it.a === actor) it.b.id else it.a.id }) } private fun partnerOf(actor: Actor): Actor? = actor.performance?.let { if (it.lead === actor) it.other else it.lead } @@ -430,9 +493,11 @@ class SceneSimulation( fun tick(seconds: Float) { val dt = if (seconds.isNaN()) 0f else seconds.coerceIn(0f, 0.1f) steps++ + time += dt for (actor in order) startQueuedPerformance(actor) for (actor in order) { if (actor.cooldown > 0f) actor.cooldown -= dt + if (actor.chatCooldown > 0f) actor.chatCooldown -= dt when (actor.phase) { Phase.WAITING -> { actor.remaining -= dt @@ -466,6 +531,21 @@ class SceneSimulation( } continue } + val talk = actor.talk + if (talk != null && performance == null) { + if (talk.a === actor && talk.conversation.started) { + val begun = talk.conversation.advance(dt) + if (begun >= 0) speak(talk, begun) + if (talk.conversation.done) endTalk(talk) + } else if (talk.b === actor && !talk.conversation.started) { + // waiting for the other to come over: face them as they come + val coming = talk.a + if (coming.phase == Phase.MOVING && hypot(coming.x - actor.x, coming.y - actor.y) <= FACE_RANGE) { + actor.facing = atan2(coming.y - actor.y, coming.x - actor.x) + } + } + if (talk.a === actor || talk.b === actor) continue + } if (actor.activity == Activity.LISTEN || (performance != null && performance.lead !== actor)) continue val before = if (performance != null) performance.seconds - actor.remaining else 0f actor.remaining -= dt @@ -506,6 +586,10 @@ class SceneSimulation( val other = nearestFree(actor) if (other != null && random.nextFloat() < partnerChance && pick(actor, other) && startPartner(actor, other, directed = false)) return } + if (chatterChance > 0f && actor.chatCooldown <= 0f && !actor.directed && actor.queue.isEmpty()) { + val other = nearestFree(actor, chat = true) + if (other != null && random.nextFloat() < chatterChance && startChat(actor, other, directed = false)) return + } if (wanderOnly) { wander(actor) return @@ -532,10 +616,40 @@ class SceneSimulation( other.partner = actor other.activity = Activity.LISTEN other.phase = Phase.ACTING + chatter?.let { words -> + val talk = Talk(actor, other, Conversation(words.conversation(actor.id, other.id, random)), directed) + actor.talk = talk + other.talk = talk + } version++ return true } + /** Line [index] of [talk] begins: its speaker's bubble (the other's is taken down). */ + private fun speak(talk: Talk, index: Int) { + val line = talk.conversation.lines[index] + val who = if (line.speaker == 0) talk.a else talk.b + val other = if (who === talk.a) talk.b else talk.a + who.spoken = line.text + who.spokenId = ++speechSerial + who.spokenUntil = time + Reading.seconds(line.text) + who.sayGestureUntil = 0f + if (other.spokenUntil > time) other.spokenUntil = time + } + + /** [talk] ran to its end: both carry on (and now and then, being friends, go into a partner animation together). */ + private fun endTalk(talk: Talk) { + val a = talk.a + val b = talk.b + release(a) + if (b.talk === talk) release(b) + a.chatCooldown = MIN_CHAT_COOLDOWN + random.nextFloat() * (MAX_CHAT_COOLDOWN - MIN_CHAT_COOLDOWN) + b.chatCooldown = MIN_CHAT_COOLDOWN + random.nextFloat() * (MAX_CHAT_COOLDOWN - MIN_CHAT_COOLDOWN) + if (!talk.directed && partnerChance > 0f && random.nextFloat() < FRIENDLY_CHANCE && free(a) && free(b) && pick(a, b)) { + startPartner(a, b, directed = false) + } + } + private fun movementOrigin(actor: Actor): Vec3 = spots[actor.target]?.entry?.takeIf { actor.phase == Phase.ACTING } ?: actor.position @@ -584,6 +698,9 @@ class SceneSimulation( actor.facing = atan2(other.position.y - actor.position.y, other.position.x - actor.position.x) other.facing = atan2(actor.position.y - other.position.y, actor.position.x - other.position.x) } + actor.talk?.let { talk -> + if (talk.a === actor && !talk.conversation.started && talk.conversation.start() == 0) speak(talk, 0) + } } private fun release(actor: Actor) { @@ -591,6 +708,12 @@ class SceneSimulation( if (actor.performance?.partnerActivity == true) actor.cooldown = MIN_COOLDOWN + random.nextFloat() * (MAX_COOLDOWN - MIN_COOLDOWN) val partner = actor.partner actor.partner = null + actor.talk?.let { talk -> + // a conversation cut short: its bubbles come down with it + for (who in arrayOf(talk.a, talk.b)) { + if (who.talk === talk) { who.talk = null; if (who.spokenUntil > time) who.spokenUntil = time } + } + } actor.performance = null actor.completedPerformance = null actor.playback = null @@ -611,17 +734,21 @@ class SceneSimulation( private fun free(o: Actor) = o.phase == Phase.WAITING && o.performance == null && !o.directed && o.cooldown <= 0f && o.queue.isEmpty() + /** Free to be talked to: idle, in nothing else, not lately in a conversation. */ + private fun freeToChat(o: Actor) = o.phase == Phase.WAITING && o.performance == null && o.talk == null && !o.directed && + o.chatCooldown <= 0f && o.queue.isEmpty() + /** The free person nearest [actor] within [PARTNER_RANGE] (ties within [TIE_YARDS]: a random one), or null. */ - private fun nearestFree(actor: Actor): Actor? { + private fun nearestFree(actor: Actor, chat: Boolean = false): Actor? { var best = Float.MAX_VALUE for (o in order) { - if (o === actor || !free(o)) continue + if (o === actor || !(if (chat) freeToChat(o) else free(o))) continue val d = hypot(o.x - actor.x, o.y - actor.y) if (d <= PARTNER_RANGE && d < best) best = d } if (best == Float.MAX_VALUE) return null val near = peopleScratch.apply { clear() } - for (o in order) if (o !== actor && free(o) && hypot(o.x - actor.x, o.y - actor.y) <= best + TIE_YARDS) near.add(o) + for (o in order) if (o !== actor && (if (chat) freeToChat(o) else free(o)) && hypot(o.x - actor.x, o.y - actor.y) <= best + TIE_YARDS) near.add(o) return if (near.size == 1) near[0] else near[random.nextInt(near.size)] } @@ -737,6 +864,11 @@ class SceneSimulation( /** Seconds before either may start another partner animation by themselves. */ const val MIN_COOLDOWN = 20f const val MAX_COOLDOWN = 60f + /** Seconds before either may start another conversation by themselves. */ + const val MIN_CHAT_COOLDOWN = 25f + const val MAX_CHAT_COOLDOWN = 60f + /** The chance a conversation that ran its course leads the two into a partner animation (when those are on). */ + const val FRIENDLY_CHANCE = 0.2f private const val DEG = 0.017453292f private val NO_PLACE = Any() } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SpeechLayout.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SpeechLayout.kt new file mode 100644 index 00000000..8eaee2b0 --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/simulation/SpeechLayout.kt @@ -0,0 +1,76 @@ +package com.logie.wifecraft.simulation + +import kotlin.math.sqrt +import kotlin.math.tan + +/** + * Where the speech bubbles go on the screen, worked out each frame on the GL thread from what the frame already has (the + * camera's eye, target and vertical field of view, as the renderer takes them: z up, near plane 0.2) and each person's + * head: [project] puts a world point on a w x h view (pixels, y down) the way the renderer draws it; [choose] keeps the + * bubbles of the speakers on screen, the nearest [MAX_BUBBLES]. Nothing allocated. Pure JVM. + */ +object SpeechLayout { + /** At most this many bubbles at once (the nearest speakers). */ + const val MAX_BUBBLES = 4 + const val NEAR = 0.2f + /** Fields per person in a layout array: screen x, screen y, depth (<= 0: off screen), shown (1) or not (0). */ + const val STRIDE = 4 + + /** + * World point [px], [py], [pz] seen from eye [ex].. toward [ax].. with [fovDeg] (vertical) on a [w] x [h] view: its + * screen x, y and depth into [out] at [at] (depth 0: behind the eye or outside the view, with a small margin). + */ + fun project(ex: Float, ey: Float, ez: Float, ax: Float, ay: Float, az: Float, fovDeg: Float, w: Float, h: Float, + px: Float, py: Float, pz: Float, out: FloatArray, at: Int) { + out[at] = 0f; out[at + 1] = 0f; out[at + 2] = 0f + if (w <= 0f || h <= 0f) return + var fx = ax - ex; var fy = ay - ey; var fz = az - ez + val fl = sqrt(fx * fx + fy * fy + fz * fz) + if (fl < 1e-6f) return + fx /= fl; fy /= fl; fz /= fl + // right = forward x up (z up; straight down or up: y up instead), then the camera's own up = right x forward + var ux = 0f; var uy = 0f; var uz = 1f + if (fz * fz > 0.998f) { uy = 1f; uz = 0f } + var sx = fy * uz - fz * uy; var sy = fz * ux - fx * uz; var sz = fx * uy - fy * ux + val sl = sqrt(sx * sx + sy * sy + sz * sz) + sx /= sl; sy /= sl; sz /= sl + val vx = sy * fz - sz * fy; val vy = sz * fx - sx * fz; val vz = sx * fy - sy * fx + val dx = px - ex; val dy = py - ey; val dz = pz - ez + val depth = dx * fx + dy * fy + dz * fz + if (depth < NEAR) return + val th = tan(fovDeg * 0.5f * 0.017453292f) + val aspect = w / h + val nx = (dx * sx + dy * sy + dz * sz) / (depth * th * aspect) + val ny = (dx * vx + dy * vy + dz * vz) / (depth * th) + if (nx < -1.05f || nx > 1.05f || ny < -1.05f || ny > 1.25f) return + out[at] = (nx + 1f) * 0.5f * w + out[at + 1] = (1f - ny) * 0.5f * h + out[at + 2] = depth + } + + /** + * Marks in [layout] (STRIDE per person, projected) which of the [speaking] people get a bubble: on screen, the nearest + * [max]; the rest are hidden. [n] people. + */ + fun choose(n: Int, speaking: BooleanArray, layout: FloatArray, max: Int = MAX_BUBBLES) { + for (i in 0 until n) layout[i * STRIDE + 3] = 0f + for (k in 0 until max) { + var best = -1 + var bestDepth = Float.MAX_VALUE + for (i in 0 until n) { + val d = layout[i * STRIDE + 2] + if (!speaking[i] || d <= 0f || layout[i * STRIDE + 3] != 0f) continue + if (d < bestDepth) { bestDepth = d; best = i } + } + if (best < 0) return + layout[best * STRIDE + 3] = 1f + } + } + + /** How high above where they stand a person's head is: standing [standing], sitting about two thirds, lying a third. */ + fun head(standing: Float, sitting: Boolean, lying: Boolean): Float = when { + lying -> standing * 0.38f + sitting -> standing * 0.7f + else -> standing + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/AnimationBrowser.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/AnimationBrowser.kt index f9409d85..cb47ce82 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/AnimationBrowser.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/AnimationBrowser.kt @@ -1,7 +1,22 @@ package com.logie.wifecraft.ui import android.view.ViewGroup +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.Canvas import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicTextField +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items @@ -32,6 +47,12 @@ internal enum class AnimationOrderMode(val label: String) { PLAY("Play now"), QUEUE("Queue"), REPEAT("Repeat"), SEQUENCE("Queue stages"), } +/** + * The animations window (Play animation in a scene, Browse animations in the library) in the front menus' look: category + * tabs ([SceneHud.animationTabs]: All, each group, Partner; Partner first while the NPC has a partner), a search, rows 56 dp + * high. A tap picks a row; [onPreview] plays it at once with the window kept open, the footer's main button plays (or + * queues, repeats) it with the chosen [AnimationOrderMode]; in the library ([onPlay] null) the picked one plays in [preview]. + */ @Composable internal fun AnimationBrowser( choices: List, @@ -39,81 +60,95 @@ internal fun AnimationBrowser( onClose: () -> Unit, onPlay: ((AnimationChoice, AnimationOrderMode) -> Unit)? = null, notice: String? = null, + /** Plays the picked one now on the NPC, the window kept open (the scene's preview). */ + onPreview: ((AnimationChoice) -> Unit)? = null, + /** The controlled NPC's partner (the Partner tab first), and the NPC itself (the subtitle). */ + partnerName: String? = null, + actorName: String? = null, ) { var query by remember { mutableStateOf("") } var selection by remember { mutableStateOf(null) } var mode by remember { mutableStateOf(AnimationOrderMode.PLAY) } + val tabs = remember(choices, partnerName) { + SceneHud.animationTabs(choices.map { it.group }, choices.any { it.participantCount == 2 }, partnerName != null) + } + var tab by remember(tabs) { mutableIntStateOf(0) } + val tabName = tabs.getOrElse(tab) { SceneHud.ALL_TAB } val selected = choices.firstOrNull { it.id == selection } - val grouped = remember(choices, query) { + val grouped = remember(choices, query, tabName) { val search = query.trim() choices.filter { - it.name.contains(search, ignoreCase = true) || it.group.contains(search, ignoreCase = true) || - it.preview.clip.category.contains(search, ignoreCase = true) || it.setting.contains(search, ignoreCase = true) + SceneHud.inTab(tabName, it.group, it.participantCount) && (it.name.contains(search, ignoreCase = true) || + it.group.contains(search, ignoreCase = true) || it.preview.clip.category.contains(search, ignoreCase = true) || + it.setting.contains(search, ignoreCase = true)) }.groupBy { it.group } } val list = rememberLazyListState() - LaunchedEffect(query) { list.scrollToItem(0) } + LaunchedEffect(query, tabName) { list.scrollToItem(0) } + val canPlay = selected != null && selected.playable Overlay(onClose) { - BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + BoxWithConstraints(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing), contentAlignment = Alignment.Center) { val width = (maxWidth - 24.dp).coerceAtMost(1000.dp) val height = (maxHeight - 24.dp).coerceAtMost(700.dp) - WowWindow(if (onPlay == null) "Browse animations" else "Play animation", onClose, Modifier.width(width).height(height)) { - Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(5.dp)) { - WowSearchBox(query, { query = it }, "Find animations", Modifier.fillMaxWidth()) + val split = width >= 640.dp + WifeWindow( + if (onPlay == null) "Browse animations" else "Play animation", onClose, Modifier.width(width).height(height), + subtitle = actorName?.let { who -> partnerName?.let { "$who with $it" } ?: who }, + tabs = tabs, tab = tab, onTab = { tab = it }, + footer = { + if (onPlay != null) { + Text(selected?.name ?: "Choose an animation", Modifier.weight(1f), style = WifeTheme.captionStyle(), maxLines = 1, + overflow = TextOverflow.Ellipsis) + if (onPreview != null) WifeButton("Preview", { selected?.let(onPreview) }, Modifier.widthIn(min = 112.dp), enabled = canPlay) + WifeButton(mode.label, { selected?.let { onPlay(it, mode) } }, Modifier.widthIn(min = 132.dp), enabled = canPlay, + kind = WifeButtonKind.PRIMARY, sound = "ok") + } else { + WifeButton("Close", onClose, Modifier.widthIn(min = 120.dp), sound = "close") + } + }, + ) { + Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapM)) { + Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { + SceneSearchField(query, { query = it.take(40) }, "Find animations", Modifier.fillMaxWidth()) + if (!split && onPlay != null) OrderModes(mode) { mode = it } LazyColumn(Modifier.weight(1f).fillMaxWidth().warScrollbar(list), list, - verticalArrangement = Arrangement.spacedBy(3.dp)) { + verticalArrangement = Arrangement.spacedBy(WifeTheme.gapXs)) { if (grouped.isEmpty()) item { - Text(if (choices.isEmpty()) "Import an animation pack to see its clips." else "No matching animations.", - Modifier.padding(8.dp), style = frizStyle(13.sp)) + WifeNote(if (choices.isEmpty()) "Import an animation pack to see its clips." else "No matching animations.", + Modifier.padding(WifeTheme.gapS)) } for ((group, entries) in grouped) { - item(key = "group:$group") { - Text("$group (${entries.size})", Modifier.padding(top = 5.dp), style = frizStyle(14.sp)) - } + if (tabName != group) item(key = "group:$group") { WifeSectionHeader("$group ${entries.size}") } items(entries, key = { it.id }) { choice -> - val count = "${choice.participantCount} NPC${if (choice.participantCount == 1) "" else "s"}" - val detail = listOfNotNull(count, choice.setting.takeIf(String::isNotBlank), - "${choice.repetitions} cycles".takeIf { choice.repetitions > 1 }, - "Missing track".takeUnless { choice.playable }).joinToString(" · ") - WowListRow(choice.name, detail, selected = choice.id == selection, onClick = { - if (onPlay != null && choice.playable) onPlay(choice, mode) else selection = choice.id - }) + AnimRow(choice, choice.id == selection, { selection = choice.id }, Modifier.padding(end = 10.dp)) } } } - } - Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) { - if (onPlay != null) { - for (row in AnimationOrderMode.entries.chunked(2)) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - for (option in row) WowCheckRow(option.label, mode == option, { mode = option }, - modifier = Modifier.weight(1f)) - } - } + if (!split && preview != null && selected != null && selected.preview.inspection.reason == null) { + Box(Modifier.weight(1f).fillMaxWidth()) { preview(selected.preview) } } + } + if (split) Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { + if (onPlay != null) OrderModes(mode) { mode = it } if (selected == null) { - val hint = when { + WifeNote(when { onPlay == null -> "Choose an animation to preview." mode == AnimationOrderMode.SEQUENCE -> "Choose a stage to queue it and its linked stages." mode == AnimationOrderMode.REPEAT -> "Choose an animation to repeat until stopped or another clip is queued." mode == AnimationOrderMode.QUEUE -> "Choose animations in the order you want them to play." - else -> "Partner clips ask for a second NPC." - } - Text(hint, - style = frizStyle(14.sp)) - if (notice != null && (mode == AnimationOrderMode.QUEUE || mode == AnimationOrderMode.SEQUENCE)) { - Text(notice, style = frizStyle(13.sp)) - } + partnerName != null -> "Partner animations play with $partnerName." + else -> "Partner animations ask for a second NPC." + }, color = WifeTheme.text) } else { - Text(selected.name, style = frizStyle(15.sp), maxLines = 2, overflow = TextOverflow.Ellipsis) - if (selected.setting.isNotEmpty()) Text("Source setting · ${selected.setting}", style = frizStyle(12.sp)) - if (selected.participantCount == 2) Text("Requires two NPCs", style = frizStyle(13.sp)) - if (!selected.playable) Text(selected.preview.inspection.reason ?: "A required actor track is missing.", style = frizStyle(13.sp)) + Text(selected.name, style = WifeTheme.titleStyle(), maxLines = 2, overflow = TextOverflow.Ellipsis) + WifeNote(details(selected), color = WifeTheme.text) + if (selected.participantCount == 2) WifeNote(partnerName?.let { "Plays with $it." } ?: "Asks for a second NPC.", color = PairRose) + if (!selected.playable) WifeNote(selected.preview.inspection.reason ?: "A required actor track is missing.", color = WifeTheme.danger) if (preview != null && selected.preview.inspection.reason == null) { Box(Modifier.weight(1f).fillMaxWidth()) { preview(selected.preview) } } } + if (notice != null) WifeNote(notice) } } } @@ -121,6 +156,83 @@ internal fun AnimationBrowser( } } +/** What a row says under an animation's name: how many NPCs, the setting, the cycles, a missing track. */ +private fun details(choice: AnimationChoice): String { + val count = "${choice.participantCount} NPC${if (choice.participantCount == 1) "" else "s"}" + return listOfNotNull(count, choice.setting.takeIf(String::isNotBlank), "${choice.repetitions} cycles".takeIf { choice.repetitions > 1 }, + "Missing track".takeUnless { choice.playable }).joinToString(" · ") +} + +/** How a scene's animation is ordered: Play now, Queue, Repeat, Queue stages (tabs of their own, 48 dp). */ +@Composable +private fun OrderModes(mode: AnimationOrderMode, onMode: (AnimationOrderMode) -> Unit) { + WifeTabs(AnimationOrderMode.entries.map { it.label }, mode.ordinal, { onMode(AnimationOrderMode.entries[it]) }) +} + +/** One animation: its name, what it is, a rose "2 NPCs" mark on partner ones; 56 dp high, lit gold when picked. */ +@Composable +private fun AnimRow(choice: AnimationChoice, picked: Boolean, onClick: () -> Unit, modifier: Modifier) { + val reduced = reduceMotion() + val edge by animateColorAsState(if (picked) WifeTheme.gold else WifeTheme.trimSoft, tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced)), label = "row") + val shape = RoundedCornerShape(WifeTheme.buttonRadius) + Row( + modifier.fillMaxWidth().heightIn(min = 56.dp).clip(shape) + .background(if (picked) Color(0x26FFD37A) else WifeTheme.slateRaised.copy(alpha = 0.55f)) + .border(if (picked) 1.5.dp else WifeTheme.trimWidth, edge, shape) + .semantics { this.selected = picked } + .warPress(sound = "select", onClick = onClick) + .padding(horizontal = WifeTheme.gapM, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapS), + ) { + Column(Modifier.weight(1f)) { + Text(choice.name, style = frizStyle(WifeTheme.label, if (!choice.playable) WifeTheme.textDim else if (picked) Color.White else WifeTheme.gold), + maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(details(choice), style = WifeTheme.captionStyle(), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + if (choice.participantCount == 2) { + val pill = RoundedCornerShape(50) + Text("2 NPCs", Modifier.clip(pill).border(1.dp, PairRose, pill).padding(horizontal = WifeTheme.gapS, vertical = 2.dp), + style = WifeTheme.captionStyle(PairRose), maxLines = 1) + } + } +} + +/** The search field in the front menus' look: a dark rounded field, a drawn magnifier, a clear x that keeps its room. */ +@Composable +internal fun SceneSearchField(value: String, onChange: (String) -> Unit, hint: String, modifier: Modifier) { + var focused by remember { mutableStateOf(false) } + val shape = RoundedCornerShape(50) + Row( + modifier.height(WifeTheme.touch).clip(shape).background(WifeTheme.track) + .border(if (focused) 1.5.dp else WifeTheme.trimWidth, if (focused) WifeTheme.gold else WifeTheme.trimSoft, shape) + .padding(start = WifeTheme.gapM), + verticalAlignment = Alignment.CenterVertically, + ) { + Canvas(Modifier.size(18.dp)) { + val r = this.size.minDimension * 0.34f + val c = Offset(r + 1.dp.toPx(), r + 1.dp.toPx()) + drawCircle(WifeTheme.trim, r, c, style = Stroke(1.6.dp.toPx())) + drawLine(WifeTheme.trim, Offset(c.x + r * 0.7f, c.y + r * 0.7f), Offset(this.size.width, this.size.height), 1.8.dp.toPx()) + } + Box(Modifier.weight(1f).padding(horizontal = WifeTheme.gapS)) { + if (value.isEmpty()) Text(hint, style = WifeTheme.bodyStyle(WifeTheme.textDim), maxLines = 1, overflow = TextOverflow.Ellipsis) + BasicTextField(value, onChange, singleLine = true, textStyle = frizStyle(WifeTheme.body, WifeTheme.text, shadow = false), + cursorBrush = SolidColor(WifeTheme.gold), modifier = Modifier.fillMaxWidth().onFocusChanged { focused = it.isFocused }) + } + // the clear button keeps its room while the field is empty (hidden, untappable): the first letter moves nothing + Box( + Modifier.size(WifeTheme.touch).graphicsLayer { alpha = if (value.isEmpty()) 0f else 1f } + .semantics { contentDescription = "Clear" } + .warPress(value.isNotEmpty(), sound = "close") { onChange("") }, + contentAlignment = Alignment.Center, + ) { + Text("×", style = frizStyle(WifeTheme.heading, WifeTheme.gold), maxLines = 1) + } + } +} + +private val PairRose = Color(0xFFE88AA8) + @Composable internal fun AnimationViewport( view: SceneView, @@ -176,7 +288,8 @@ internal fun AnimationViewport( mapped == 0 -> "$name could not play this clip." else -> null } - if (message != null) Text(message, Modifier.background(Color(0xDD191719)).padding(6.dp), style = frizStyle(14.sp)) + if (message != null) Text(message, Modifier.clip(RoundedCornerShape(WifeTheme.buttonRadius)).background(WifeTheme.slate) + .padding(horizontal = WifeTheme.gapM, vertical = 6.dp), style = WifeTheme.bodyStyle()) } val matched = mapped val summary = when { @@ -185,10 +298,10 @@ internal fun AnimationViewport( animation.omittedChannels -> "$name · Some source channels omitted" else -> "$name · $matched tracks matched" } - Text(summary, style = frizStyle(12.sp), maxLines = 1, overflow = TextOverflow.Ellipsis) - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { - RedButton("Replay", { replay++ }, Modifier.weight(1f), enabled = ready, textSize = 12.sp) - RedButton("Rotate", { angle = (angle + 1) % 4 }, Modifier.weight(1f), enabled = ready, textSize = 12.sp) + Text(summary, style = WifeTheme.captionStyle(), maxLines = 1, overflow = TextOverflow.Ellipsis) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { + WifeButton("Replay", { replay++ }, Modifier.weight(1f), enabled = ready) + WifeButton("Rotate", { angle = (angle + 1) % 4 }, Modifier.weight(1f), enabled = ready) } } } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/DownloadOptions.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/DownloadOptions.kt index a55d4876..e3384f91 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/DownloadOptions.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/DownloadOptions.kt @@ -14,6 +14,10 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.logie.wifecraft.data.AssetDownloads +import com.logie.wifecraft.audio.MixLevels +import androidx.compose.animation.Crossfade +import androidx.compose.animation.core.tween +import androidx.compose.ui.text.style.TextOverflow import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.Job import kotlinx.coroutines.delay @@ -57,8 +61,12 @@ fun StateFlow.collectThrottled(urgent: (T?, T) -> Boolean = { _, _ -> fal return throttled.collectAsStateWithLifecycle(value) } -private enum class Page(val label: String) { DOWNLOADS("Downloads"), SOUND("Sound"), MODS("Mods") } +private enum class Page(val label: String) { SOUND("Sound"), DOWNLOADS("Downloads"), MODS("Mods") } +/** + * Options, in the front menus' look (WifeWindow): Sound (the game's own Sound page: Enable Sound, Master, Music, Ambience, Sound + * effects, Dialog; then the partner sounds), Downloads (the speed, the packs, the bar) and Mods. Every change applies at once. + */ @Composable fun DownloadOptions( progress: AssetDownloads.Progress?, @@ -67,69 +75,89 @@ fun DownloadOptions( canDownload: Boolean, speed: Int, onSpeed: (Int) -> Unit, - volume: Int, - onVolume: (Int) -> Unit, + /** The Sound page's levels and their change (applied at once, kept by the caller). */ + mix: MixLevels, + onMix: (MixLevels) -> Unit, onDownload: (List) -> Unit, onPause: () -> Unit, onClose: () -> Unit, mods: @Composable () -> Unit, - /** Extra blocks under the Sound page's slider (the partner sounds). */ + /** Extra blocks under the Sound page's sliders (the partner sounds). */ sound: @Composable () -> Unit = {}, ) { - var page by remember { mutableStateOf(Page.DOWNLOADS) } + var page by remember { mutableStateOf(Page.SOUND) } + val reduced = reduceMotion() Overlay(onClose) { BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { val layout = ChromeLayout.of(maxWidth.value, maxHeight.value) - WowWindow("Options", onClose, Modifier.width(layout.optionsW.dp).height(layout.optionsH.dp), - tabs = { Page.entries.forEach { entry -> WowTab(entry.label, entry == page, { page = entry }) } }) { - Column( - Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - when (page) { - Page.DOWNLOADS -> { - Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Text("Download speed", Modifier.weight(1f), style = frizStyle(14.sp)) - WowDropdown(OptionsModel.DOWNLOAD.firstOrNull { it.first == speed }?.second ?: "$speed at once", - OptionsModel.DOWNLOAD, onSpeed, Modifier.weight(1.1f)) + WifeWindow( + "Options", onClose, Modifier.width(layout.optionsW.dp).height(layout.optionsH.dp), + tabs = Page.entries.map { it.label }, tab = page.ordinal, onTab = { page = Page.entries[it] }, + footer = { + if (page != Page.DOWNLOADS && downloading) Text( + "Downloading ${progress?.pack?.label?.lowercase() ?: "game files"}…", + style = WifeTheme.captionStyle(), maxLines = 1, modifier = Modifier.weight(1f), + ) + WifeButton("Okay", onClose, Modifier.widthIn(min = 132.dp), kind = WifeButtonKind.PRIMARY, sound = "ok") + }, + ) { + // one page gives way to the next (a short cross-fade), each with its own scroll from its top + Crossfade(page, Modifier.fillMaxWidth().weight(1f), animationSpec = tween(MenuMotion.duration(MenuMotion.PAGE_MS, reduced)), label = "page") { shown -> + Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(WifeTheme.gapXs)) { + when (shown) { + Page.SOUND -> { + WifeSwitchRow("Enable Sound", mix.enabled, { onMix(mix.copy(enabled = it)) }, detail = "Silent whenever Wifecraft is in the background") + WifeSectionHeader("Volume") + val on = mix.enabled + WifeSliderRow("Master", mix.master, { onMix(mix.copy(master = it)) }, enabled = on) + WifeSliderRow("Music", mix.music, { onMix(mix.copy(music = it)) }, enabled = on) + WifeSliderRow("Ambience", mix.ambience, { onMix(mix.copy(ambience = it)) }, enabled = on) + WifeSliderRow("Sound effects", mix.effects, { onMix(mix.copy(effects = it)) }, enabled = on) + WifeSliderRow("Dialog", mix.dialog, { onMix(mix.copy(dialog = it)) }, enabled = on) + WifeNote("The music dips while someone speaks. The game's music and sounds are fetched from wago.tools as they are first played.") + WifeSectionHeader("Partner sounds") + sound() } - // The block is always here, the same height (its texts keep their lines): starting a download - // never pushes the buttons down under the finger, and Pause takes Download all's place. - val current = progress - val fraction = current?.fraction?.coerceIn(0f, 1f) ?: 0f - Text(current?.let { "${it.pack.label} (${it.packNumber} of ${it.packCount})" } ?: "Nothing downloading", - style = frizStyle(15.sp), maxLines = 1) - LoadingBar(fraction, Modifier.fillMaxWidth().height(32.dp).semantics { - progressBarRangeInfo = if (current != null && current.total == 0 && downloading) ProgressBarRangeInfo.Indeterminate - else ProgressBarRangeInfo(fraction, 0f..1f) - }) - val line = current?.let { - val mb = "%.1f MB".format(it.bytes / 1_000_000.0) - val checked = if (it.total > 0) " · ${it.done} of ${it.total} entries checked" else " · Finding files…" - val failed = if (it.failed > 0) " · ${it.failed} failed" else "" - "${it.files} files downloaded ($mb)$checked$failed" - } ?: "Pick what to download; files already here are skipped." - Text(line, style = frizStyle(12.sp, Color.White), minLines = 2, maxLines = 2) - Text(status ?: "", style = frizStyle(12.sp, Color.White), minLines = 2, maxLines = 3) - if (downloading) { - RedButton("Pause", onPause, Modifier.fillMaxWidth()) - } else { - RedButton("Download all", { onDownload(AssetDownloads.Pack.entries) }, Modifier.fillMaxWidth(), enabled = canDownload) + Page.DOWNLOADS -> { + Row(Modifier.fillMaxWidth().heightIn(min = WifeTheme.touch), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapM)) { + Text("Download speed", Modifier.weight(1f), style = WifeTheme.labelStyle(), maxLines = 2) + WowDropdown(OptionsModel.DOWNLOAD.firstOrNull { it.first == speed }?.second ?: "$speed at once", + OptionsModel.DOWNLOAD, onSpeed, Modifier.weight(1.1f)) + } + // The block is always here, the same height (its texts keep their lines): starting a download + // never pushes the buttons down under the finger, and Pause takes Download all's place. + val current = progress + val fraction = current?.fraction?.coerceIn(0f, 1f) ?: 0f + WifeSectionHeader("Game files") + Text(current?.let { "${it.pack.label} (${it.packNumber} of ${it.packCount})" } ?: "Nothing downloading", + style = WifeTheme.labelStyle(WifeTheme.gold), maxLines = 1, overflow = TextOverflow.Ellipsis) + WifeProgress(fraction, Modifier.padding(vertical = WifeTheme.gapXs).semantics { + progressBarRangeInfo = if (current != null && current.total == 0 && downloading) ProgressBarRangeInfo.Indeterminate + else ProgressBarRangeInfo(fraction, 0f..1f) + }) + val line = current?.let { + val mb = "%.1f MB".format(it.bytes / 1_000_000.0) + val checked = if (it.total > 0) " · ${it.done} of ${it.total} entries checked" else " · Finding files…" + val failed = if (it.failed > 0) " · ${it.failed} failed" else "" + "${it.files} files downloaded ($mb)$checked$failed" + } ?: "Pick what to download; files already here are skipped." + Text(line, style = WifeTheme.captionStyle(WifeTheme.text), minLines = 2, maxLines = 2) + Text(status ?: "", style = WifeTheme.captionStyle(WifeTheme.text), minLines = 2, maxLines = 3) + if (downloading) { + WifeButton("Pause", onPause, Modifier.fillMaxWidth(), kind = WifeButtonKind.PRIMARY) + } else { + WifeButton("Download all", { onDownload(AssetDownloads.Pack.entries) }, Modifier.fillMaxWidth(), enabled = canDownload, kind = WifeButtonKind.PRIMARY) + } + for (pack in AssetDownloads.Pack.entries) { + WifeButton(pack.label, { onDownload(listOf(pack)) }, Modifier.fillMaxWidth(), enabled = canDownload && !downloading) + } + if (!canDownload) WifeNote("Gather the character tables first.") } - for (pack in AssetDownloads.Pack.entries) { - RedButton(pack.label, { onDownload(listOf(pack)) }, Modifier.fillMaxWidth(), enabled = canDownload && !downloading) - } - if (!canDownload) Text("Gather the character tables first.", style = frizStyle(12.sp, Color.White)) + Page.MODS -> mods() } - Page.SOUND -> { WowSliderRow("Sound effects", volume, onVolume); sound() } - Page.MODS -> mods() } } - if (page != Page.DOWNLOADS && downloading) { - Text("Downloading ${progress?.pack?.label?.lowercase() ?: "game files"}…", - style = frizStyle(12.sp), modifier = Modifier.padding(vertical = 6.dp)) - } } } } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/MenuModel.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/MenuModel.kt index f6b3960b..1b265337 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/MenuModel.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/MenuModel.kt @@ -414,3 +414,47 @@ data class ChromeLayout( fun rows(n: Int, cols: Int): Int = ceil(n / cols.toFloat()).toInt() } } + +// ------------------------------------------------------------------------------------------------ the front menus (WifeTheme) + +/** + * The title's layout on a screen [wDp] x [hDp] (the Fold's inner screen about 832 x 750, its cover 411 x 960 standing or + * 960 x 411 on its side): the menu down the left over the backdrop on a wide screen, centred on a narrow one; a smaller + * crest and title on a short one. [buttonW] fits inside the screen's margins; nothing is wider than the screen. + */ +data class TitleLayout( + val centered: Boolean, + val compact: Boolean, + val crestDp: Float, + val titleSp: Float, + val buttonW: Float, + val padH: Float, + val padTop: Float, +) + +object FrontLayout { + /** The screen's side margin and the most a front-menu button is wide. */ + const val MARGIN = 16f + const val BUTTON_MAX = 300f + + fun title(wDp: Float, hDp: Float): TitleLayout { + val centered = wDp < 600f + val compact = hDp < 520f + val padH = if (centered) MARGIN else 48f + return TitleLayout( + centered = centered, + compact = compact, + crestDp = if (compact) 52f else 76f, + titleSp = if (compact) 38f else if (wDp < 380f) 42f else 52f, + buttonW = min(BUTTON_MAX, max(0f, wDp - 2 * padH)), + padH = padH, + padTop = if (compact) 16f else 40f, + ) + } + + /** A slider row puts its label above the slider when the row is narrower than this (the cover screen standing). */ + fun sliderStacked(rowWDp: Float): Boolean = rowWDp < 340f + + /** The Options window's tabs as a scrolling strip rather than equal parts when each part would be narrower than a touch. */ + fun tabsScroll(rowWDp: Float, tabs: Int): Boolean = tabs > 0 && rowWDp / tabs < 96f +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/MenuMotion.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/MenuMotion.kt index e03bab1f..6c02404e 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/MenuMotion.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/MenuMotion.kt @@ -94,3 +94,36 @@ object ListKeys { } } } + +/** + * The front menus' (WifeTheme's) own motion: a press's glow and a hover's, the title's backdrop drifting slowly (a scale and a + * pan, as the game's login screen breathes), the motes rising over it. None of it moves under reduced motion. + */ +object FrontMotion { + const val GLOW_MS = 140 + const val TAB_MS = MenuMotion.PAGE_MS + /** One slow breath of the backdrop, there and back. */ + const val DRIFT_MS = 26_000 + const val DRIFT_SCALE = 0.045f + const val DRIFT_PAN = 0.018f + const val MOTES = 18 + + /** The backdrop at [phase] 0..1 of a breath: its scale (1 to 1 + [DRIFT_SCALE]) and its pan (fractions of its size). */ + fun drift(phase: Float, reduced: Boolean): Triple { + if (reduced) return Triple(1f, 0f, 0f) + val p = phase - kotlin.math.floor(phase) + val s = (1f - kotlin.math.cos(p * 2.0 * Math.PI).toFloat()) / 2f // 0 -> 1 -> 0, smoothly + return Triple(1f + DRIFT_SCALE * s, DRIFT_PAN * (s - 0.5f) * 2f, -DRIFT_PAN * 0.5f * s) + } + + /** Mote [i] of [MOTES] at [phase] 0..1: where it is (x, y as 0..1 of the screen) and how bright (0..1); stable per [i]. */ + fun mote(i: Int, phase: Float): Triple { + val h = ((i * 2654435761L) and 0xFFFFFFFFL).toFloat() / 4294967296f // 0..1, fixed per mote + val speed = 0.6f + h * 0.8f + val t = (phase * speed + h) % 1f + val x = ((h * 7.31f) % 1f) * 0.9f + 0.05f + 0.02f * kotlin.math.sin((t * 6.28f + i).toDouble()).toFloat() + val y = 1.05f - t * 1.1f + val a = kotlin.math.sin((t * Math.PI)).toFloat().coerceIn(0f, 1f) * (0.35f + 0.4f * h) + return Triple(x, y, a) + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/Menus.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/Menus.kt index c6954fd3..39188871 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/Menus.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/Menus.kt @@ -1,216 +1,38 @@ package com.logie.wifecraft.ui -import androidx.compose.foundation.Image -import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.text.BasicTextField -import androidx.compose.material3.Checkbox -import androidx.compose.material3.RadioButton -import androidx.compose.material3.RadioButtonDefaults -import androidx.compose.material3.Slider -import androidx.compose.material3.SliderDefaults +import androidx.compose.foundation.layout.widthIn import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.animation.Crossfade -import androidx.compose.animation.core.tween -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.SolidColor -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.foundation.gestures.detectTapGestures -import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.logie.wifecraft.R -import com.logie.wifecraft.story.LogEntry -import java.text.DateFormat -import java.util.Date - -// Overlay (the dimmed backdrop with one panel, moving in and out) is in MenuMotionUi.kt. - -/** What was said, newest at the bottom. */ -@Composable -fun LogPanel(entries: List, nameOf: (String) -> String, onBack: () -> Unit) { - MetalPanel(Modifier.width(720.dp).heightIn(max = 360.dp)) { - Column { - Text("What Was Said", style = frizStyle(16.sp), modifier = Modifier.align(Alignment.CenterHorizontally)) - // opens already at the newest line (no jump from the top after the first frame); new lines glide into view - val state = rememberLazyListState(initialFirstVisibleItemIndex = (entries.size - 1).coerceAtLeast(0)) - LaunchedEffect(entries.size) { if (entries.isNotEmpty() && state.firstVisibleItemIndex < entries.size - 1) state.animateScrollToItem(entries.size - 1) } - LazyColumn(Modifier.weight(1f, fill = false).heightIn(max = 260.dp), state = state) { - items(entries.size, key = { it }, contentType = { "line" }) { i -> val e = entries[i] - Column(Modifier.padding(vertical = 4.dp)) { - val name = nameOf(e.who) - if (name.isNotEmpty()) Text(name, style = frizStyle(12.sp)) - Text(e.text, style = frizStyle(14.sp, Color.White)) - } - } - } - WowButton("Back", onBack, Modifier.align(Alignment.CenterHorizontally).padding(top = 6.dp), width = 150.dp, height = 38.dp) - } - } -} -/** - * Options, as the game's settings window: the categories down its left side (Game, Sound, Graphics, Interface, Advanced last: - * [OptionsModel]) and the chosen page's rows beside them (gold labels; check boxes, sliders and dropdowns as the game draws - * them), Okay at the foot. Game holds the Imports page (Ralia's mod, Alternate Female Options, the body options, the undead - * skins, the Sims 4 skeleton) and the interface art's state. A narrow window puts the categories in a dropdown over the page. - * Every change applies at once (Okay closes). - */ -@Composable -fun OptionsWindow( - textSpeed: Int, onTextSpeed: (Int) -> Unit, - parchment: Boolean, onParchment: (Boolean) -> Unit, - wifiOnly: Boolean, onWifiOnly: (Boolean) -> Unit, - /** Files fetched at once by the first launch's gathering (24, 48 or 96). */ - downloadSpeed: Int, onDownloadSpeed: (Int) -> Unit, - musicVolume: Int, onMusicVolume: (Int) -> Unit, - ambienceVolume: Int, onAmbienceVolume: (Int) -> Unit, - soundVolume: Int, onSoundVolume: (Int) -> Unit, - voiceVolume: Int, onVoiceVolume: (Int) -> Unit, - /** Soft body: 0 Off, 1 Subtle, 2 Natural, 3 Strong (applies at once). */ - softBody: Int, onSoftBody: (Int) -> Unit, - onBack: () -> Unit, - /** The creator's imports (the title's and the editor's Options; none while a story plays). */ - imports: (@Composable () -> Unit)? = null, - /** The Sims 4 skeleton's state ("loaded" or "not loaded") and the way to Import Animations, where it is chosen. */ - simsSkeleton: String? = null, - onImportAnims: (() -> Unit)? = null, - /** The editor's interface art: how much is here, what failed, Retry (WarArtRow). */ - interfaceArt: (@Composable () -> Unit)? = null, - /** The game's files: what is missing, and Gather (the first launch's screen). */ - gameFiles: String? = null, - onGather: (() -> Unit)? = null, - /** The partner animations' sounds: the On box, the volume, the status and the folder's buttons (PartnerSoundsSection). */ - partnerSounds: (@Composable () -> Unit)? = null, -) { - var page by rememberSaveable { mutableStateOf(OptionsPage.SOUND) } - val reduced = reduceMotion() - BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { - val layout = ChromeLayout.of(maxWidth.value, maxHeight.value) - val side = OptionsModel.sideList(layout.optionsW) - WowWindow("Options", onBack, Modifier.width(layout.optionsW.dp).height(layout.optionsH.dp)) { - Row(Modifier.weight(1f)) { - if (side) Column(Modifier.width(170.dp)) { - for (c in OptionsPage.CATEGORIES) { - val on = c == page || page.parent == c - Box( - Modifier.fillMaxWidth().height(48.dp).background(if (on) Color(0x28FFD100) else Color.Transparent) - .border(1.dp, if (on) Color(0x8CFFD100) else Color.Transparent).warPress { page = c }.padding(horizontal = 14.dp), - contentAlignment = Alignment.CenterStart, - ) { Text(c.label, style = frizStyle(15.sp, if (on) Color.White else WowColors.gold)) } - } - } - if (side) Box(Modifier.padding(horizontal = 12.dp).width(1.5.dp).fillMaxHeight().background(Color(0xFF64583F))) - // one page gives way to the next (a short cross-fade), each page with its own scroll from its top - Crossfade(page, Modifier.weight(1f).fillMaxHeight(), animationSpec = tween(MenuMotion.duration(MenuMotion.PAGE_MS, reduced)), label = "page") { shown -> - Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(4.dp)) { - if (!side) WowDropdown(shown.label, OptionsPage.CATEGORIES.map { it to it.label }, { page = it }, Modifier.fillMaxWidth()) - Row(verticalAlignment = Alignment.CenterVertically) { - if (shown.parent != null) TextAction("‹ ${shown.parent!!.label}", { page = shown.parent!! }) - Text(shown.label, style = frizStyle(18.sp), modifier = Modifier.padding(vertical = 8.dp)) - } - var importsShown = false - for (k in OptionsModel.rows(shown)) when (k) { - OptionKey.MUSIC -> WowSliderRow(k.label, musicVolume, onMusicVolume) - OptionKey.AMBIENCE -> WowSliderRow(k.label, ambienceVolume, onAmbienceVolume) - OptionKey.EFFECTS -> WowSliderRow(k.label, soundVolume, onSoundVolume) - OptionKey.VOICES -> WowSliderRow(k.label, voiceVolume, onVoiceVolume) - OptionKey.SOFT_BODY -> ChoiceRow(k.label, "Chest, belly, rear and thighs hang and bounce as she moves") { - WowDropdown(OptionsModel.SOFT_BODY[softBody.coerceIn(0, 3)], OptionsModel.SOFT_BODY.mapIndexed { i, l -> i to l }, onSoftBody, Modifier.fillMaxWidth()) - } - OptionKey.DOWNLOAD_SPEED -> ChoiceRow(k.label, "Files at once; it slows itself when wago.tools asks for less") { - WowDropdown(OptionsModel.DOWNLOAD.firstOrNull { it.first == downloadSpeed }?.second ?: "$downloadSpeed at once", OptionsModel.DOWNLOAD, onDownloadSpeed, Modifier.fillMaxWidth()) - } - OptionKey.TEXT_SPEED -> WowSliderRow(k.label, textSpeed, onTextSpeed, if (textSpeed >= 120) "at once" else "$textSpeed/s", 15..120) - OptionKey.PARCHMENT -> WowCheckRow(k.label, parchment, onParchment, detail = "Instead of Legion's dark talking head") - OptionKey.WIFI_ONLY -> WowCheckRow(k.label, wifiOnly, onWifiOnly, detail = "A look's own files still come as it is shown") - OptionKey.GAME_FILES -> ChoiceRow(k.label, gameFiles ?: "All here") { - if (onGather != null) RedButton("Gather", onGather, Modifier.fillMaxWidth()) - } - OptionKey.IMPORTS -> Row( - Modifier.fillMaxWidth().heightIn(min = 48.dp).warPress { page = OptionsPage.IMPORTS }, - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - Text(k.label, style = frizStyle(15.sp)) - Text("Ralia's mod, Alternate Female Options, Body options, Undead skins, the Sims 4 skeleton", style = frizStyle(11.sp, WowColors.grey), maxLines = 2) - } - Text("›", style = frizStyle(22.sp), modifier = Modifier.padding(horizontal = 10.dp)) - } - OptionKey.INTERFACE_ART -> interfaceArt?.invoke() - OptionKey.PARTNER_SOUNDS -> partnerSounds?.invoke() - OptionKey.RALIA, OptionKey.ALTERNATE_FEMALE, OptionKey.BODY, OptionKey.UNDEAD -> if (!importsShown) { - importsShown = true - if (imports != null) imports() else Text("The imports are set from the title's or the editor's Options.", style = frizStyle(13.sp, Color.White)) - } - OptionKey.SIMS_SKELETON -> ChoiceRow(k.label, simsSkeleton ?: "Chosen in Import Animations") { - if (onImportAnims != null) RedButton("Import Animations", onImportAnims, Modifier.fillMaxWidth(), textSize = 13.sp) - } - } - } - } - } - Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.End) { - RedButton("Okay", onBack, Modifier.width(150.dp)) - } - } - } -} +// Overlay (the dimmed backdrop with one panel, moving in and out) is in MenuMotionUi.kt; the front menus' kit (WifeWindow, +// WifeButton...) in WowWidgets.kt. -/** A settings row: the gold label (and a grey line under it), its control on the right. */ +/** Updates from the repository's releases, in a small front-menu window: what is out, Install. */ @Composable -private fun ChoiceRow(label: String, detail: String?, control: @Composable () -> Unit) { - Row(Modifier.fillMaxWidth().heightIn(min = 56.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { - Column(Modifier.weight(1f)) { - Text(label, style = frizStyle(15.sp), maxLines = 1) - if (detail != null) Text(detail, style = frizStyle(11.sp, WowColors.grey), maxLines = 2) - } - Box(Modifier.width(220.dp)) { control() } +fun UpdatePanel(status: String, canInstall: Boolean, onInstall: () -> Unit, onBack: () -> Unit) { + WifeWindow( + "Updates", onBack, Modifier.widthIn(max = 520.dp).padding(16.dp), + subtitle = "Wifecraft updates itself from its releases", + footer = { + if (canInstall) WifeButton("Install", onInstall, Modifier.weight(1f), kind = WifeButtonKind.PRIMARY, sound = "ok") + WifeButton("Okay", onBack, Modifier.weight(1f), kind = if (canInstall) WifeButtonKind.SECONDARY else WifeButtonKind.PRIMARY, sound = "close") + }, + ) { + Text(status, style = WifeTheme.bodyStyle(), modifier = Modifier.fillMaxWidth().padding(vertical = WifeTheme.gapXs)) } } +/** A short message in a front-menu window (the problem box): the words, and Close. */ @Composable -fun goldCheckbox() = androidx.compose.material3.CheckboxDefaults.colors( - checkedColor = WowColors.gold, uncheckedColor = WowColors.gold.copy(alpha = 0.7f), checkmarkColor = Color.Black, -) - -/** Updates from the repository's releases, in a small WoW window: what is out, Install. */ -@Composable -fun UpdatePanel(status: String, canInstall: Boolean, onInstall: () -> Unit, onBack: () -> Unit) { - WowWindow("Updates", onBack, Modifier.widthIn(max = 520.dp).padding(16.dp)) { - Text(status, style = frizStyle(14.sp, Color.White), modifier = Modifier.padding(vertical = 6.dp)) - Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) { - if (canInstall) RedButton("Install", onInstall, Modifier.weight(1f)) - RedButton("Okay", onBack, Modifier.weight(1f)) - } +fun WifeMessage(title: String, message: String, onClose: () -> Unit) { + WifeWindow( + title, onClose, Modifier.widthIn(max = 500.dp).padding(16.dp), + footer = { WifeButton("Close", onClose, Modifier.widthIn(min = 132.dp), kind = WifeButtonKind.PRIMARY, sound = "close") }, + ) { + Text(message, style = WifeTheme.bodyStyle(), modifier = Modifier.fillMaxWidth()) } } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/PartnerSoundsUi.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/PartnerSoundsUi.kt index 12db0552..d6a25121 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/PartnerSoundsUi.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/PartnerSoundsUi.kt @@ -73,22 +73,18 @@ fun PartnerSoundsSection( } } - Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text("Partner sounds", style = frizStyle(16.sp)) - WowCheckRow("Partner sounds", on, onOn, detail = "Play the sounds of partner animations from your files") - WowSliderRow("Volume", volume, onVolume) + Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(WifeTheme.gapXs)) { + WifeSwitchRow("Partner sounds", on, onOn, detail = "Play the sounds of partner animations from your files") + WifeSliderRow("Volume", volume, onVolume, enabled = on) val status = remember(version) { sounds.status() } - Text(if (busy) "Adding…" else status.summary() + if (status.formats.isEmpty()) "" else " (" + status.formats.joinToString(", ") + ")", style = frizStyle(13.sp, WowColors.white)) - Text( - "Put sound files here that match the sound names in your animation mods (ogg, wav, mp3). The game's own EA audio formats are not decoded yet.", - style = frizStyle(11.sp, WowColors.grey), - ) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 2.dp)) { - WowButton("Add sounds", { + Text(if (busy) "Adding…" else status.summary() + if (status.formats.isEmpty()) "" else " (" + status.formats.joinToString(", ") + ")", style = WifeTheme.bodyStyle()) + WifeNote("Put sound files here that match the sound names in your animation mods (ogg, wav, mp3). The game's own EA audio formats are not decoded yet.") + Row(horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapS), modifier = Modifier.fillMaxWidth().padding(top = WifeTheme.gapXs)) { + WifeButton("Add sounds", { picker.launch(arrayOf("audio/*", "application/zip", "application/x-zip-compressed", "application/octet-stream")) - }, enabled = !busy, width = 150.dp, height = 36.dp) - WowButton("Remove all", { run { sounds.clear(); "Removed" } }, enabled = !busy && status.count > 0, width = 140.dp, height = 36.dp) + }, Modifier.weight(1f), enabled = !busy) + WifeButton("Remove all", { run { sounds.clear(); "Removed" } }, Modifier.weight(1f), enabled = !busy && status.count > 0) } - message?.let { Text(it, style = frizStyle(12.sp, Color(0xFFFF6A5A))) } + message?.let { Text(it, style = WifeTheme.captionStyle(WifeTheme.danger)) } } } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneBrowsers.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneBrowsers.kt index 8bc1b825..a403e8a4 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneBrowsers.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneBrowsers.kt @@ -23,6 +23,10 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView +import androidx.compose.foundation.border +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.style.TextOverflow import com.logie.wifecraft.editor.Actor import com.logie.wifecraft.engine.LocationLoader import com.logie.wifecraft.engine.SceneView @@ -45,7 +49,7 @@ internal fun SceneBrowser( val cards: @Composable (Modifier) -> Unit = { area -> if (locations.isEmpty()) { Box(area, contentAlignment = Alignment.Center) { - Text("No scenes available", style = frizStyle(14.sp)) + Text("No scenes available", style = WifeTheme.bodyStyle(WifeTheme.textDim)) } } else { LazyVerticalGrid( @@ -55,11 +59,7 @@ internal fun SceneBrowser( ) { items(locations, key = { it.id }, contentType = { 0 }) { entry -> Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.TopCenter) { - ItemCard( - AnnotatedString(entry.name), icon, 76.dp, entry.id == location, - favourite = false, onClick = { onLocation(entry.id) }, onFavourite = null, - selection = entry.id == location, - ) + WifeCard(entry.name, icon, 76.dp, entry.id == location, onClick = { onLocation(entry.id) }) } } } @@ -83,7 +83,6 @@ internal fun SceneBrowser( private fun LocationPreview(preset: LocationInfo, view: SceneView, loader: LocationLoader, modifier: Modifier) { var retry by remember(preset.id) { mutableIntStateOf(0) } var completed by remember(preset.id, retry) { mutableStateOf(null) } - val art = LocalArt.current DisposableEffect(view, preset.id, retry) { view.showCity(false) view.frame = checkNotNull(preset.views["inside"]?.camera) to emptyMap() @@ -95,28 +94,27 @@ private fun LocationPreview(preset: LocationInfo, view: SceneView, loader: Locat } } Column(modifier, verticalArrangement = Arrangement.spacedBy(5.dp)) { - Text(preset.name, style = frizStyle(15.sp), maxLines = 1) - Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { - Box(Modifier.matchParentSize().padding(5.dp).background(Color.Black)) { + Text(preset.name, style = WifeTheme.headingStyle(), maxLines = 1, overflow = TextOverflow.Ellipsis) + val shape = RoundedCornerShape(WifeTheme.buttonRadius) + Box(Modifier.weight(1f).fillMaxWidth().clip(shape).background(Color.Black), contentAlignment = Alignment.Center) { + Box(Modifier.matchParentSize()) { BrowserSurface(view, Modifier.matchParentSize()) } if (completed != true) { Column( - Modifier.matchParentSize().padding(5.dp).background(Color(0xEE15110C)).padding(horizontal = 12.dp), + Modifier.matchParentSize().background(WifeTheme.slateDeep).padding(horizontal = 12.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { if (completed == false) { - Text("Scene preview unavailable", style = frizStyle(13.sp), textAlign = TextAlign.Center) - RedButton("Retry preview", { retry++ }) + Text("Scene preview unavailable", style = WifeTheme.bodyStyle(), textAlign = TextAlign.Center) + WifeButton("Retry preview", { retry++ }) } else { PreviewProgress(loader, preset.id) } } } - Canvas(Modifier.matchParentSize()) { - drawMetalFrame(art, minOf(14.dp.toPx(), size.minDimension / 2f)) - } + Box(Modifier.matchParentSize().border(1.dp, WifeTheme.trim.copy(alpha = 0.8f), shape)) } } } @@ -133,10 +131,10 @@ private fun PreviewProgress(loader: LocationLoader, id: String) { } val (done, total) = counts val downloading = total > 0 && done < total - Text(if (downloading) "Downloading scene $done / $total" else "Loading scene…", style = frizStyle(13.sp), textAlign = TextAlign.Center) + Text(if (downloading) "Downloading scene $done / $total" else "Loading scene…", style = WifeTheme.bodyStyle(), textAlign = TextAlign.Center) // the bar's room is kept while there is nothing to count: the text doesn't jump up and down as it comes and goes - Box(Modifier.fillMaxWidth().height(12.dp)) { - if (downloading) LoadingBar(done.toFloat() / total, Modifier.fillMaxSize()) + Box(Modifier.fillMaxWidth().padding(top = 6.dp).height(12.dp)) { + if (downloading) WifeProgress(done.toFloat() / total) } } @@ -157,19 +155,19 @@ internal fun NpcBrowser( BoxWithConstraints(modifier) { // Thumbnails render off-screen on the same GL context that the creator and live scene use. BrowserSurface(view, Modifier.size(1.dp)) - val size = if (maxHeight < 235.dp) 72.dp else 96.dp + val side = if (maxHeight < 235.dp) 72.dp else 96.dp val newNpc: @Composable (Modifier) -> Unit = { area -> - RedButton("Create NPC", onCreate, area, textSize = 13.sp) + WifeButton("Create NPC", onCreate, area, kind = WifeButtonKind.PRIMARY, sound = "create") } val rosterGrid: @Composable (Modifier) -> Unit = { area -> if (shown.isEmpty()) { Box(area, contentAlignment = Alignment.Center) { Text(if (search.isBlank()) "Create an NPC to add to the scene." else "No NPCs match your search.", - style = frizStyle(14.sp)) + style = WifeTheme.bodyStyle(WifeTheme.textDim), textAlign = TextAlign.Center) } } else { LazyVerticalGrid( - columns = GridCells.Adaptive(size + 8.dp), + columns = GridCells.Adaptive(side + 8.dp), modifier = area, horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(8.dp), @@ -194,11 +192,7 @@ internal fun NpcBrowser( } val inCast = actor.id in cast Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.TopCenter) { - ItemCard( - AnnotatedString(actor.name), picture ?: icon, size, inCast, - favourite = false, onClick = { onToggle(actor.id) }, onFavourite = null, - enabled = inCast || cast.size < 6, selection = inCast, - ) + WifeCard(actor.name, picture ?: icon, side, inCast, onClick = { onToggle(actor.id) }, enabled = inCast || cast.size < 6) } } } @@ -207,15 +201,15 @@ internal fun NpcBrowser( if (maxWidth >= 410.dp) { Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(12.dp)) { Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) { - WowSearchBox(search, { search = it }, "Find NPCs", Modifier.fillMaxWidth()) + SceneSearchField(search, { search = it.take(40) }, "Find NPCs", Modifier.fillMaxWidth()) rosterGrid(Modifier.weight(1f).fillMaxWidth()) } Column(Modifier.width(148.dp).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(6.dp)) { newNpc(Modifier.fillMaxWidth()) - Text("Cast ${cast.size} / 6", style = frizStyle(13.sp)) + WifeSectionHeader("Cast ${cast.size} / 6") Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) { for (actor in roster) if (actor.id in cast) { - WowCheckRow(actor.name, true, { onToggle(actor.id) }, Modifier.fillMaxWidth()) + WifeChip(actor.name, { onToggle(actor.id) }) } } } @@ -224,15 +218,15 @@ internal fun NpcBrowser( Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(6.dp)) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { - WowSearchBox(search, { search = it }, "Find NPCs", Modifier.weight(1f)) + SceneSearchField(search, { search = it.take(40) }, "Find NPCs", Modifier.weight(1f)) newNpc(Modifier) } Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Text("Cast ${cast.size} / 6", style = frizStyle(13.sp), maxLines = 1) + Text("Cast ${cast.size} / 6", style = WifeTheme.labelStyle(WifeTheme.gold), maxLines = 1) if (cast.isNotEmpty()) { - Row(Modifier.weight(1f).horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Row(Modifier.weight(1f).horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { for (actor in roster) if (actor.id in cast) { - WowCheckRow(actor.name, true, { onToggle(actor.id) }) + WifeChip(actor.name, { onToggle(actor.id) }) } } } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneHud.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneHud.kt new file mode 100644 index 00000000..99fba770 --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneHud.kt @@ -0,0 +1,136 @@ +package com.logie.wifecraft.ui + +import kotlin.math.ceil +import kotlin.math.max +import kotlin.math.min + +// Pure Kotlin, no android.* and no Compose (JVM-tested: unit-tests/.../ui/SceneHudTest): the live scene's HUD in the front +// menus' look (SceneSessionScreen draws it). What the action bar offers for the controlled NPC and in which order, its +// pages of six, the line of help, the clock, where the bars go on each of the Fold's screens, and the Play animation +// window's category tabs. + +/** What an action-bar slot does. */ +enum class HudOrder { WALK, PLAY, PARTNER, SAY, CHAT, STOP_REPEAT, CLEAR_QUEUE, RELEASE, USE, FREE_WILL } + +/** One slot of the action bar: what it does, its words, [lit] while it is on (Walk), [target] the object it uses. */ +data class HudSlot(val order: HudOrder, val label: String, val lit: Boolean = false, val target: String? = null) { + /** Stable per slot (two objects' Use slots differ by their target). */ + val key: String get() = if (target == null) order.name else "${order.name}:$target" +} + +/** + * Where the HUD goes on a screen [w] x [h] dp: the cast as party frames down the left ([castSide]) or a strip under the top + * bar; the action bar's [cols] x [rows] slots, each [slotW] wide, [barH] high with its gaps (the same whether the slots are + * all there or not: the line above it never moves). + */ +data class HudLayout( + val castSide: Boolean, + val castW: Float, + val castH: Float, + val cols: Int, + val rows: Int, + val slotW: Float, + val barW: Float, + val barH: Float, +) + +object SceneHud { + /** Slots shown at once (one page of the bar). */ + const val SLOTS = 6 + const val SLOT_H = 48f + const val GAP = 8f + const val MARGIN = 8f + /** The page arrows' column at the bar's end (kept even with one page: the bar never shifts). */ + const val PAGER_W = 48f + const val TOP_H = 56f + /** The narrowest slot for six in a row; narrower screens get two rows of three. */ + const val SLOT_MIN = 104f + const val SLOT_MAX = 140f + + fun layout(w: Float, h: Float): HudLayout { + val castSide = w >= 600f + val room = max(0f, w - 2 * MARGIN - PAGER_W - GAP) + val cols = if (room >= SLOTS * SLOT_MIN + (SLOTS - 1) * GAP) SLOTS else SLOTS / 2 + val rows = SLOTS / cols + val slotW = min(SLOT_MAX, max(0f, (room - (cols - 1) * GAP) / cols)) + val barW = cols * slotW + (cols - 1) * GAP + GAP + PAGER_W + val barH = rows * SLOT_H + (rows - 1) * GAP + return HudLayout(castSide, if (castSide) 188f else 156f, if (castSide) 56f else 56f, cols, rows, slotW, barW, barH) + } + + /** + * The controlled NPC's orders, most used first: Walk (tap the floor), Play animation, Partner animation (with a + * partner), Say, Chat with (with someone else in the scene), Stop repeat and Clear queue (while there is one), Release, + * then the scene's objects ([uses]: target to words) and Free will. + */ + fun orders( + walking: Boolean, + partner: Boolean, + others: Int, + repeating: Boolean, + queued: Int, + uses: List> = emptyList(), + ): List = buildList { + add(HudSlot(HudOrder.WALK, "Walk", lit = walking)) + add(HudSlot(HudOrder.PLAY, "Play animation")) + if (partner) add(HudSlot(HudOrder.PARTNER, "Partner animation")) + add(HudSlot(HudOrder.SAY, "Say…")) + if (others > 0) add(HudSlot(HudOrder.CHAT, "Chat with…")) + if (repeating) add(HudSlot(HudOrder.STOP_REPEAT, "Stop repeat")) + if (queued > 0) add(HudSlot(HudOrder.CLEAR_QUEUE, "Clear queue ($queued)")) + add(HudSlot(HudOrder.RELEASE, "Release")) + for ((target, words) in uses) add(HudSlot(HudOrder.USE, words, target = target)) + add(HudSlot(HudOrder.FREE_WILL, "Free will")) + } + + fun pages(slots: Int): Int = max(1, ceil(slots / SLOTS.toFloat()).toInt()) + + /** [page] kept within the pages there are (the bar shortened under it). */ + fun clampPage(page: Int, slots: Int): Int = page.coerceIn(0, pages(slots) - 1) + + /** The slots of [page] (at most [SLOTS]). */ + fun page(slots: List, page: Int): List = slots.drop(clampPage(page, slots.size) * SLOTS).take(SLOTS) + + /** The line over the bar: what a tap does now. */ + fun hint(selected: Boolean, partner: Boolean, cast: Int, walking: Boolean): String = when { + !selected -> if (cast > 0) "Tap an NPC to direct them." else "" + walking && !partner && cast > 1 -> "Tap the floor to walk there, another NPC to make them the partner." + walking -> "Tap the floor to walk there." + !partner && cast > 1 -> "Tap another NPC to make them the partner." + else -> "" + } + + /** The clock on the top bar, as the game's: "9:05 PM", or "21:05" on a 24-hour phone. */ + fun clock(hour: Int, minute: Int, h24: Boolean): String { + val m = minute.coerceIn(0, 59).toString().padStart(2, '0') + val hr = hour.coerceIn(0, 23) + if (h24) return "${hr.toString().padStart(2, '0')}:$m" + val h12 = if (hr % 12 == 0) 12 else hr % 12 + return "$h12:$m ${if (hr < 12) "AM" else "PM"}" + } + + /** The two-person animations' own tab in the Play animation window. */ + const val PARTNER_TAB = "Partner" + const val ALL_TAB = "All" + + /** + * The Play animation window's tabs: All and every [groups] in order, and Partner (the two-person ones) when there are + * any; Partner first when the controlled NPC has a partner ([partnerFirst]), last otherwise. A group already named + * Partner is the Partner tab. + */ + fun animationTabs(groups: List, hasPairs: Boolean, partnerFirst: Boolean): List { + val rest = groups.distinct().filterNot { it.equals(PARTNER_TAB, ignoreCase = true) || it.equals(ALL_TAB, ignoreCase = true) } + return when { + !hasPairs -> listOf(ALL_TAB) + rest + partnerFirst -> listOf(PARTNER_TAB, ALL_TAB) + rest + else -> listOf(ALL_TAB) + rest + PARTNER_TAB + } + } + + /** Whether an animation of [group] for [people] NPCs belongs under [tab]. */ + fun inTab(tab: String, group: String, people: Int): Boolean = when (tab) { + ALL_TAB -> true + PARTNER_TAB -> people == 2 + else -> group == tab + } +} diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneSessionScreen.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneSessionScreen.kt index b416b8d1..eb97b9ee 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneSessionScreen.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SceneSessionScreen.kt @@ -5,6 +5,7 @@ import android.os.Looper import android.view.ViewGroup import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.Crossfade +import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.animateFloatAsState @@ -14,20 +15,41 @@ import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.activity.compose.BackHandler +import androidx.compose.foundation.Canvas import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.input.pointer.pointerInput @@ -42,6 +64,7 @@ import com.logie.wifecraft.anim.PERFORMANCE_SCALE import com.logie.wifecraft.anim.PairAnim import com.logie.wifecraft.anim.animationChoices import com.logie.wifecraft.anim.animationSequence +import com.logie.wifecraft.catalog.EmotePlayability import com.logie.wifecraft.engine.Clock import com.logie.wifecraft.simulation.PartnerSound import com.logie.wifecraft.simulation.PerformanceOrder @@ -62,6 +85,7 @@ import com.logie.wifecraft.simulation.Activity import com.logie.wifecraft.simulation.InteractionSpot import com.logie.wifecraft.simulation.LiveScene import com.logie.wifecraft.simulation.ModelEmotes +import com.logie.wifecraft.simulation.PartnerEmotes import com.logie.wifecraft.simulation.PartnerFrequency import com.logie.wifecraft.simulation.PartnerPair import com.logie.wifecraft.simulation.PartnerSoundSink @@ -69,14 +93,24 @@ import com.logie.wifecraft.simulation.SceneSnapshot import com.logie.wifecraft.simulation.TouchGesture import com.logie.wifecraft.simulation.TwoFingers import com.logie.wifecraft.simulation.SceneObject +import com.logie.wifecraft.simulation.Chatter +import com.logie.wifecraft.simulation.ChatterFrequency +import com.logie.wifecraft.simulation.Races +import com.logie.wifecraft.simulation.SceneControl +import com.logie.wifecraft.simulation.Speaker +import com.logie.wifecraft.simulation.SpeechLayout +import com.logie.wifecraft.creator.Sex +import androidx.compose.ui.layout.onSizeChanged import com.logie.wifecraft.story.CameraPose import com.logie.wifecraft.story.Vec3 +import kotlinx.coroutines.delay import kotlinx.coroutines.withTimeoutOrNull import kotlin.math.abs import kotlin.random.Random enum class SetupStep(val title: String) { LOCATION("Choose Scene"), CAST("Choose NPCs"), OBJECTS("Choose objects") } +/** The scene's setup in the front menus' look: one [WifeWindow] a step (the scene, the cast, the objects and how lively). */ @Composable fun SceneSetupScreen( step: SetupStep, @@ -101,41 +135,55 @@ fun SceneSetupScreen( onPartner: (PartnerFrequency) -> Unit = {}, /** How many enabled partner animations the library has (0: the Warcraft emotes are used). */ partnerPairs: Int = 0, + /** How often idle NPCs go and talk to each other, speech bubbles and all (kept with the scene setup). */ + chatter: ChatterFrequency = ChatterFrequency.SOMETIMES, + onChatter: (ChatterFrequency) -> Unit = {}, ) { BackHandler(onBack = onBack) - BoxWithConstraints(Modifier.fillMaxSize().background(Color.Black), contentAlignment = Alignment.Center) { + Box(Modifier.fillMaxSize().background(Color.Black)) { WifecraftMenuBackdrop(Modifier.fillMaxSize()) - val layout = ChromeLayout.of(maxWidth.value, maxHeight.value) - WowWindow(step.title, onBack, Modifier.width(layout.optionsW.dp).height(layout.optionsH.dp), body = WindowBody.TRANSLUCENT) { - val body = Modifier.weight(1f).fillMaxWidth() - when (step) { - SetupStep.LOCATION -> SceneBrowser(locations, location, onLocation, checkNotNull(previewView), locationLoader, body) - SetupStep.CAST -> NpcBrowser(roster, cast, onToggleActor, onCreate, checkNotNull(previewView), portraits, portraitActor, body) - SetupStep.OBJECTS -> Column(body.verticalScroll(key(step) { rememberScrollState() }), verticalArrangement = Arrangement.spacedBy(6.dp)) { - val available = locations.firstOrNull { it.id == location }?.interactions.orEmpty() - for (item in SceneObject.entries) if (available.any { it.item == item.name }) { - WowCheckRow(item.label, item in objects, { onToggleObject(item) }) - } - RedButton("Animation library", onAnimations) - Text("Partner", color = Color(0xFFF4DFBD), style = frizStyle(15.sp)) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - for (f in PartnerFrequency.entries) key(f) { - WowTab(f.label, f == partner, { onPartner(f) }, Modifier.weight(1f)) + BoxWithConstraints(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing), contentAlignment = Alignment.Center) { + val layout = ChromeLayout.of(maxWidth.value, maxHeight.value) + WifeWindow( + step.title, onBack, Modifier.width(layout.optionsW.dp).height(layout.optionsH.dp), + subtitle = "Step ${step.ordinal + 1} of ${SetupStep.entries.size}", + footer = { + WifeButton("Back", onBack, Modifier.widthIn(min = 120.dp), sound = "close") + WifeButton( + if (step == SetupStep.OBJECTS) "Begin scene" else "Next", onNext, Modifier.widthIn(min = 140.dp), + enabled = when (step) { + SetupStep.LOCATION -> location != null + SetupStep.CAST -> cast.isNotEmpty() + SetupStep.OBJECTS -> true + }, + kind = WifeButtonKind.PRIMARY, sound = if (step == SetupStep.OBJECTS) "ok" else "click", + ) + }, + ) { + val body = Modifier.weight(1f).fillMaxWidth() + when (step) { + SetupStep.LOCATION -> SceneBrowser(locations, location, onLocation, checkNotNull(previewView), locationLoader, body) + SetupStep.CAST -> NpcBrowser(roster, cast, onToggleActor, onCreate, checkNotNull(previewView), portraits, portraitActor, body) + SetupStep.OBJECTS -> Column(body.verticalScroll(key(step) { rememberScrollState() }), verticalArrangement = Arrangement.spacedBy(WifeTheme.gapXs)) { + val available = locations.firstOrNull { it.id == location }?.interactions.orEmpty() + val items = SceneObject.entries.filter { item -> available.any { it.item == item.name } } + WifeSectionHeader("Objects") + if (items.isEmpty()) WifeNote("This scene has nothing to sit, rest or read at.") + for (item in items) key(item) { + WifeSwitchRow(item.label, item in objects, { onToggleObject(item) }) } + WifeSectionHeader("Partner") + WifeTabs(PartnerFrequency.entries.map { it.label }, partner.ordinal, { onPartner(PartnerFrequency.entries[it]) }) + WifeNote(if (partnerPairs > 0) "$partnerPairs partner animation${if (partnerPairs == 1) "" else "s"} imported" + else "None imported: NPCs share Warcraft emotes instead") + WifeSectionHeader("Chatter") + WifeTabs(ChatterFrequency.entries.map { it.label }, chatter.ordinal, { onChatter(ChatterFrequency.entries[it]) }) + WifeNote("How often NPCs walk up to each other and talk, in speech bubbles") + WifeSectionHeader("Animations") + WifeButton("Animation library", onAnimations, Modifier.fillMaxWidth(), sound = "open") } - WowNote(if (partnerPairs > 0) "$partnerPairs partner animation${if (partnerPairs == 1) "" else "s"} imported" - else "Partner: none imported: using Warcraft emotes") } } - Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) { - RedButton("Back", onBack, Modifier.weight(1f)) - RedButton(if (step == SetupStep.OBJECTS) "Begin scene" else "Next", onNext, Modifier.weight(1f), - enabled = when (step) { - SetupStep.LOCATION -> location != null - SetupStep.CAST -> cast.isNotEmpty() - SetupStep.OBJECTS -> true - }) - } } } } @@ -145,9 +193,10 @@ private data class PendingAnimation(val owner: String, val choice: AnimationChoi /** * The live scene. Nothing here changes every frame: the simulation, the people's motion and the camera run on the GL * thread ([LiveScene] driving the [SceneView] through its [FrameDriver]); this screen gets a [SceneSnapshot] only when what - * its menus show changed (at most ten a second), and sends the player's orders and touches back. Its bars keep one size - * (the 3D view is never resized by a selection or a longer label), and an overlay covers the view until the scene is - * loaded and its first frames are drawn, then fades. + * its menus show changed (at most ten a second), and sends the player's orders and touches back. The view fills the + * screen and never resizes; the HUD floats over it in the front menus' look ([SceneHud] places it): a top bar (the place, + * the clock, the scene menu), the cast as party frames, a line of help with the partner chip, and an action bar of six + * slots a page. An overlay covers the view until the scene is loaded and its first frames are drawn, then fades. */ @Composable fun LiveSceneScreen( @@ -178,44 +227,66 @@ fun LiveSceneScreen( partnerSounds: PartnerSoundSink = PartnerSoundSink.NONE, /** Fetches a game animation's files for an actor key (Dresser.fetchAnim): the fallback's emotes. */ fetchAnim: (String, Int) -> Unit = { _, _ -> }, + /** How often idle NPCs go and talk to each other (their lines in speech bubbles). */ + chatter: ChatterFrequency = ChatterFrequency.SOMETIMES, + /** Opens Options over the scene (the scene menu's Options; null: the menu has none). */ + onSettings: (() -> Unit)? = null, ) { // the scene's seed: one per scene, so a scene replays the same way from it (the tests use it so) val seed = remember(cast, objects) { Random.nextLong() } val choices = remember(clips, pairs) { animationChoices(clips) + pairs.filter { it.enabled }.map { it.choice() } } // what NPCs pick from by themselves: the library's enabled pairs and the authors' two-actor performances val partnerPairs = remember(pairs, choices) { PartnerPair.enabled(pairs) + choices.mapNotNull { PartnerPair.of(it) } } + // what the NPCs say to each other: their names, races and sexes, and the place + val words = remember(cast, locationName) { + Chatter(cast.associate { it.id to Speaker(it.name, it.appearance.raceId, it.appearance.sex == Sex.FEMALE) }, locationName) + } val live = remember(cast, objects) { val origin = toStage(Vec3(0f, 0f, 0f)) LiveScene(cast.map { it.id }, objects, emptyMap(), camera, origin.x, origin.y, origin.z, stageRotation, Random(seed), wanderOnly = true, route = { from, to -> view.glWalkRoute(toStage(from), toStage(to))?.map(toLocal) }, - pairs = partnerPairs, emotes = emotes, partnerChance = partner.chance) + pairs = partnerPairs, emotes = emotes, partnerChance = partner.chance, + chatter = words, chatterChance = chatter.chance) } + // the speech bubbles: the GL thread lays them out each frame, the overlay draws them; each person's line now + val speechSpots = remember(live) { SpeechSpots(live.count) } + val lines = remember(live) { mutableStateListOf().apply { repeat(live.count) { add(null) } } } + val heads = remember(cast) { FloatArray(cast.size) { Races.headHeight(cast[it].appearance.raceId) } } // the clips every playback key names (GL thread reads it): the orders' (request) and the partner pairs' roles val playback = remember(live) { ConcurrentHashMap() } - LaunchedEffect(live, partnerPairs, partner, emotes) { + LaunchedEffect(live, partnerPairs, partner, emotes, chatter) { for (p in partnerPairs) { playback[PlaybackKeys.pair(p.id, 0)] = lifted(p.a.copy(loop = false), p.slotA.z) playback[PlaybackKeys.pair(p.id, 1)] = lifted(p.b.copy(loop = false), p.slotB.z) } - live.command { sim -> sim.pairs = partnerPairs; sim.partnerChance = partner.chance; sim.emotes = emotes } + live.command { sim -> sim.pairs = partnerPairs; sim.partnerChance = partner.chance; sim.emotes = emotes; sim.chatterChance = chatter.chance } } SideEffect { live.camera.room = camera } var snapshot by remember(live) { mutableStateOf(live.snapshot()) } - var selected by remember { mutableStateOf(null) } + // who the player controls and that NPC's partner (SceneControl: a tap on another NPC makes it the partner) + var control by remember { mutableStateOf(SceneControl()) } + val selected = control.selected + val partnerId = control.partner var npcCamera by remember { mutableStateOf(false) } var ending by remember { mutableStateOf(false) } var choosingAnimation by remember { mutableStateOf(null) } var choosingPartner by remember { mutableStateOf(null) } - // "Send to partner": the selected NPC waits for the player to tap the one it goes to - var sending by remember { mutableStateOf(false) } + // the Say list open for this NPC, the Chat with list, the scene menu (the top bar's gear) + var saying by remember { mutableStateOf(null) } + var chatting by remember { mutableStateOf(null) } + var menu by remember { mutableStateOf(false) } val names = remember(cast) { cast.associate { it.id to it.name } } val active = selected?.let { id -> snapshot.people.firstOrNull { it.id == id } } BackHandler { - if (choosingPartner != null) choosingPartner = null + if (saying != null) saying = null + else if (chatting != null) chatting = null + else if (choosingPartner != null) choosingPartner = null else if (choosingAnimation != null) choosingAnimation = null + else if (menu) menu = false else if (npcCamera) npcCamera = false - else if (selected != null) selected = null + else if (partnerId != null) control = control.clearPartner() + else if (selected != null) control = control.release() else ending = true } @@ -262,9 +333,13 @@ fun LiveSceneScreen( // GL thread: the frame's time on the engine's clock; both of a pair start their clips from this one value var frameMs = 0 val emoting = BooleanArray(live.count) + // main thread: the talking gestures' files asked for once each + val gestureFiles = HashSet() val sink = object : LiveScene.Sink { - override fun camera(eyeX: Float, eyeY: Float, eyeZ: Float, atX: Float, atY: Float, atZ: Float, fov: Float) = + override fun camera(eyeX: Float, eyeY: Float, eyeZ: Float, atX: Float, atY: Float, atZ: Float, fov: Float) { view.glCamera(eyeX, eyeY, eyeZ, atX, atY, atZ, fov) + speechSpots.layout(eyeX, eyeY, eyeZ, atX, atY, atZ, fov) // the bubbles follow the heads with this camera + } override fun place(index: Int, x: Float, y: Float, z: Float, facing: Float, furniture: SceneObject?, sx: Float, sy: Float, sz: Float) { val pose = when (furniture?.action) { @@ -273,6 +348,19 @@ fun LiveSceneScreen( else -> FurniturePose.FLOOR } view.glPlace(keys[index], x, y, z, facing, pose, sx, sy, sz) + val standing = heads.getOrElse(index) { 2.05f } + speechSpots.headAt(index, sx, sy, sz + SpeechLayout.head(standing, pose == FurniturePose.SIT, pose == FurniturePose.REST)) + } + + override fun speech(index: Int, text: String?, id: Long) { + if (index in speechSpots.speaking.indices) speechSpots.speaking[index] = text != null + main.post { if (index in lines.indices) lines[index] = text } + } + + override fun gesture(index: Int, animation: Int) { + val key = keys[index] + view.glAnimate(key, animation) // this very frame + main.post { if (gestureFiles.add(index.toLong() shl 32 or animation.toLong())) fetch(key, animation) } } override fun playback(index: Int, clip: ClipPlayback?) { @@ -281,10 +369,12 @@ fun LiveSceneScreen( val wasEmote = emoting[index] emoting[index] = emote != null if (emote != null) { - // a Warcraft emote both play (no imported pair fits): its files, then the game animation from this frame + // a Warcraft emote both play (no imported pair fits): its files, then the game animation from this frame, + // held only when it is a held one (Dance); a wave or a bow plays once val start = frameMs + val held = emoteHeld(emote) view.glPlayAnimation(key, null) - main.post { fetch(key, emote); view.anim(key, emote, true, start) } + main.post { fetch(key, emote); view.anim(key, emote, held, start) } } else { view.glPlayAnimation(key, clip?.let { playback[it.clip] }) if (wasEmote) { val start = frameMs; main.post { view.anim(key, 0, true, start) } } // back to standing @@ -336,15 +426,16 @@ fun LiveSceneScreen( fun sendToPartner(id: String, otherId: String) = live.order { sim -> if (sim.partner(id, otherId)) null else "${names[otherId]} can't join ${names[id]} now." } - LaunchedEffect(selected) { if (selected == null) sending = false } + fun chatWith(id: String, otherId: String) = live.order { sim -> + if (sim.chat(id, otherId)) null else "There’s no clear path to ${names[otherId]}." + } + // the partner leaves the scene's cast or the cast changes: drop who is gone + LaunchedEffect(cast) { control = control.keep(cast.map { it.id }) } val onTap by rememberUpdatedState<(Hit?) -> Unit>({ hit -> when (hit?.kind) { - Hit.Kind.ACTOR -> cast.firstOrNull { actorKey(it.id) == hit.key }?.let { other -> - val from = selected - if (sending && from != null && other.id != from) { sending = false; sendToPartner(from, other.id) } - else selected = other.id - } + // nobody controlled: take control; one controlled: the tapped NPC becomes (or, tapped again, stops being) its partner + Hit.Kind.ACTOR -> cast.firstOrNull { actorKey(it.id) == hit.key }?.let { other -> control = control.tapNpc(other.id) } Hit.Kind.LOCATION, Hit.Kind.PROP -> if (ready) { val item = hit.key?.let(objectHits::get) val id = selected @@ -355,9 +446,9 @@ fun LiveSceneScreen( if (ready && npcCamera && id != null) { val destination = toLocal(Vec3(hit.x, hit.y, hit.z)) live.order { sim -> if (sim.walk(id, destination)) null else "There’s no clear path to that spot." } - } else if (!npcCamera) selected = null + } else if (!npcCamera) control = control.release() } - null -> if (!npcCamera) selected = null + null -> if (!npcCamera) control = control.release() } }) val orbiting by rememberUpdatedState(npcCamera) @@ -371,170 +462,477 @@ fun LiveSceneScreen( revealed = true } - Column(Modifier.fillMaxSize().background(SceneGround)) { - Row( - Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text(locationName, Modifier.weight(1f), color = Color(0xFFF4DFBD), style = frizStyle(17.sp), maxLines = 1, - overflow = TextOverflow.Ellipsis) - // always there (greyed with nobody selected): the bar never shifts when someone is chosen - RedButton(if (npcCamera) "Room camera" else "NPC camera", { npcCamera = !npcCamera }, Modifier.width(156.dp), - enabled = active != null) - RedButton("End scene", { ending = true }, Modifier.width(132.dp)) + // the action bar: the controlled NPC's orders, six a page + val uses = remember(objects) { SceneObject.entries.filter { it in objects }.map { it.name to useLabel(it) } } + val mate = partnerId?.takeIf { it != active?.id } + val slots = if (active == null) emptyList() + else SceneHud.orders(npcCamera, mate != null, cast.size - 1, active.repeating, active.queued, uses) + var page by remember { mutableIntStateOf(0) } + LaunchedEffect(selected) { page = 0 } + fun act(id: String, slot: HudSlot) { + when (slot.order) { + HudOrder.WALK -> npcCamera = !npcCamera + HudOrder.PLAY -> choosingAnimation = id + HudOrder.PARTNER -> partnerId?.let { sendToPartner(id, it) } + HudOrder.SAY -> saying = id + HudOrder.CHAT -> { + val others = cast.filter { it.id != id } + if (others.size == 1) chatWith(id, others[0].id) else chatting = id + } + HudOrder.STOP_REPEAT -> live.order { sim -> sim.stopRepeat(id); null } + HudOrder.CLEAR_QUEUE -> live.order { sim -> sim.clearQueue(id); null } + HudOrder.RELEASE -> control = control.release() + HudOrder.USE -> SceneObject.entries.firstOrNull { it.name == slot.target }?.let { use(id, it) } + HudOrder.FREE_WILL -> live.order { sim -> sim.freeWill(id); null } } - Box(Modifier.fillMaxWidth().weight(1f)) { - AndroidView( - { (view.parent as? ViewGroup)?.removeView(view); view }, - Modifier.fillMaxSize().pointerInput(view, live) { - val slop = 8.dp.toPx() - val velocity = FloatArray(2) - awaitEachGesture { - val down = awaitFirstDown(requireUnconsumed = false) - val gesture = TouchGesture(slop) - gesture.down(down.position.x, down.position.y, down.uptimeMillis) - var last = down.position - var lastTime = down.uptimeMillis - var twoFingers = false - var span = 0f - var angle = 0f - var twist = 0f - while (true) { - val event = awaitPointerEvent() - val pressed = event.changes.filter { it.pressed } - event.changes.firstOrNull()?.let { lastTime = it.uptimeMillis } - if (pressed.isEmpty()) break - if (pressed.size >= 2) { - val a = pressed[0].position - val b = pressed[1].position - val nowSpan = TwoFingers.span(a.x, a.y, b.x, b.y) - val nowAngle = TwoFingers.angle(a.x, a.y, b.x, b.y) - if (!twoFingers || span <= 0f) { - twoFingers = true - gesture.multi() - } else if (orbiting) { - live.camera.pinch(nowSpan / span) - // a twist turns the orbit once it is plainly a twist (a pinch's wobble never does) - twist += TwoFingers.turn(angle, nowAngle) - if (abs(twist) > TWIST_DEADZONE) live.camera.twist(TwoFingers.turn(angle, nowAngle)) - pressed.forEach { it.consume() } - } - span = nowSpan - angle = nowAngle - } else { - span = 0f // one finger of a pinch lifted: the next two-finger move starts afresh - if (!twoFingers) { - val finger = pressed.firstOrNull { it.id == down.id } ?: pressed[0] - last = finger.position - if (gesture.move(last.x, last.y, finger.uptimeMillis) && orbiting) { - live.camera.dragBy(gesture.dx, gesture.dy, size.height.toFloat()) - finger.consume() - } + } + fun slotEnabled(id: String, slot: HudSlot): Boolean = when (slot.order) { + HudOrder.PLAY, HudOrder.PARTNER, HudOrder.SAY, HudOrder.CHAT -> ready + HudOrder.USE -> ready && SceneObject.entries.firstOrNull { it.name == slot.target }?.let { snapshot.available(it, id) } == true + else -> true + } + + val reduced = reduceMotion() + Box(Modifier.fillMaxSize().background(SceneGround)) { + AndroidView( + { (view.parent as? ViewGroup)?.removeView(view); view }, + Modifier.fillMaxSize().onSizeChanged { speechSpots.width = it.width.toFloat(); speechSpots.height = it.height.toFloat() }.pointerInput(view, live) { + val slop = 8.dp.toPx() + val velocity = FloatArray(2) + awaitEachGesture { + val down = awaitFirstDown(requireUnconsumed = false) + val gesture = TouchGesture(slop) + gesture.down(down.position.x, down.position.y, down.uptimeMillis) + var last = down.position + var lastTime = down.uptimeMillis + var twoFingers = false + var span = 0f + var angle = 0f + var twist = 0f + while (true) { + val event = awaitPointerEvent() + val pressed = event.changes.filter { it.pressed } + event.changes.firstOrNull()?.let { lastTime = it.uptimeMillis } + if (pressed.isEmpty()) break + if (pressed.size >= 2) { + val a = pressed[0].position + val b = pressed[1].position + val nowSpan = TwoFingers.span(a.x, a.y, b.x, b.y) + val nowAngle = TwoFingers.angle(a.x, a.y, b.x, b.y) + if (!twoFingers || span <= 0f) { + twoFingers = true + gesture.multi() + } else if (orbiting) { + live.camera.pinch(nowSpan / span) + // a twist turns the orbit once it is plainly a twist (a pinch's wobble never does) + twist += TwoFingers.turn(angle, nowAngle) + if (abs(twist) > TWIST_DEADZONE) live.camera.twist(TwoFingers.turn(angle, nowAngle)) + pressed.forEach { it.consume() } + } + span = nowSpan + angle = nowAngle + } else { + span = 0f // one finger of a pinch lifted: the next two-finger move starts afresh + if (!twoFingers) { + val finger = pressed.firstOrNull { it.id == down.id } ?: pressed[0] + last = finger.position + if (gesture.move(last.x, last.y, finger.uptimeMillis) && orbiting) { + live.camera.dragBy(gesture.dx, gesture.dy, size.height.toFloat()) + finger.consume() } } } - when { - gesture.up(lastTime) -> view.pick(last.x, last.y, size.width, size.height) { onTap(it) } - gesture.kind == TouchGesture.Kind.DRAG && orbiting -> { - gesture.velocity(lastTime, velocity) - live.camera.release(velocity[0], velocity[1], size.height.toFloat()) - } - else -> live.camera.letGo() + } + when { + gesture.up(lastTime) -> view.pick(last.x, last.y, size.width, size.height) { onTap(it) } + gesture.kind == TouchGesture.Kind.DRAG && orbiting -> { + gesture.velocity(lastTime, velocity) + live.camera.release(velocity[0], velocity[1], size.height.toFloat()) } + else -> live.camera.letGo() } - }, - ) - ZoomButtons(npcCamera, live, Modifier.align(Alignment.CenterEnd).padding(end = 8.dp)) - SceneLoadingCover(!revealed, locationName, status, progress) - // a problem after loading (a prop without a surface, a file that wouldn't come): a fixed-width note on top - ProblemNote(status.takeIf { revealed }, Modifier.align(Alignment.TopCenter).padding(8.dp)) - } - // the cast, the orders and the notice: each row a fixed height, whether someone is selected or not - Row( - Modifier.fillMaxWidth().height(48.dp).horizontalScroll(rememberScrollState()).padding(horizontal = 12.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - for (person in snapshot.people) key(person.id) { - val doing = person.partner?.let { "With ${names[it]}" } ?: person.activity.description - WowTab("${names[person.id]} · $doing", person.id == selected, - { selected = if (person.id == selected) null else person.id }, Modifier.width(CAST_TAB_WIDTH)) - } - } - Crossfade(active?.id, Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 12.dp), label = "orders") { id -> - if (id == null) { - Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterStart) { - Text("Select an NPC to direct them.", color = Color.LightGray) } - } else { - Row(Modifier.fillMaxSize().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp), - verticalAlignment = Alignment.CenterVertically) { - RedButton("Play animation", { choosingAnimation = id }, enabled = ready) - if (active?.id == id && active.repeating) { - RedButton("Stop repeat", { live.order { sim -> sim.stopRepeat(id); null } }) + }, + ) + SpeechBubbles(speechSpots, remember(cast) { cast.map { it.name } }, lines, + partnerId?.let { id -> cast.indexOfFirst { it.id == id } } ?: -1) + SceneLoadingCover(!revealed, locationName, status, progress) + + // the HUD, inside the screen's safe area (cut-outs, the hinge's bars, the gesture bar) + val shown by animateFloatAsState(if (revealed) 1f else 0f, tween(MenuMotion.duration(MenuMotion.WINDOW_IN_MS, reduced)), label = "hud") + BoxWithConstraints(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing)) { + val hud = SceneHud.layout(maxWidth.value, maxHeight.value) + SceneTopBar(locationName, { menu = true }, Modifier.align(Alignment.TopCenter).fillMaxWidth()) + if (shown > 0f) { + val people = snapshot.people + val castModifier = Modifier.graphicsLayer { alpha = shown } + if (hud.castSide) { + Column( + castModifier.align(Alignment.TopStart).padding(start = SceneHud.MARGIN.dp, top = (SceneHud.TOP_H + 4f).dp, + bottom = (hud.barH + 2 * SceneHud.SLOT_H + 3 * SceneHud.MARGIN).dp) + .width(hud.castW.dp).verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + for (person in people) key(person.id) { + CastFrame(names[person.id] ?: "", doing(person, names), person.id == selected, person.id == partnerId, + { control = control.tapCast(person.id) }, Modifier.fillMaxWidth().height(hud.castH.dp)) + } } - if (active?.id == id && active.queued > 0) { - RedButton("Clear queue (${active.queued})", { live.order { sim -> sim.clearQueue(id); null } }) + } else { + Row( + castModifier.align(Alignment.TopStart).padding(top = SceneHud.TOP_H.dp).fillMaxWidth() + .horizontalScroll(rememberScrollState()).padding(horizontal = SceneHud.MARGIN.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + for (person in people) key(person.id) { + CastFrame(names[person.id] ?: "", doing(person, names), person.id == selected, person.id == partnerId, + { control = control.tapCast(person.id) }, Modifier.width(hud.castW.dp).height(hud.castH.dp)) + } } - for (item in objects) key(item) { - val action = when (item) { - SceneObject.CHAIR -> "Sit in chair" - SceneObject.COUCH -> "Sit on couch" - SceneObject.BED -> "Rest on bed" - SceneObject.TABLE -> "Read a book" + } + ZoomButtons(npcCamera, live, Modifier.align(Alignment.CenterEnd).padding(end = SceneHud.MARGIN.dp)) + // the line of help (or the last refusal) with the partner chip, and the action bar: a fixed height, so + // choosing someone or a longer line never moves anything + Column( + Modifier.align(Alignment.BottomCenter).graphicsLayer { alpha = shown }.padding(bottom = SceneHud.MARGIN.dp) + .width(hud.barW.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + val hint = SceneHud.hint(active != null, mate != null, cast.size, npcCamera) + Row(Modifier.fillMaxWidth().height(WifeTheme.touch), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { + AnimatedVisibility(mate != null && active != null, enter = fadeIn(tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced))), + exit = fadeOut(tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced)))) { + WifeChip("Partner: ${rememberHeld(mate)?.let { names[it] } ?: ""}", { control = control.clearPartner() }) + } + val line = (snapshot.notice ?: hint.takeIf { active != null }).orEmpty() + Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) { + if (line.isNotEmpty()) HudLine(line) } - RedButton(action, { use(id, item) }, enabled = ready && snapshot.available(item, id)) } - for (other in cast) if (other.id != id) key(other.id) { - RedButton("Chat with ${other.name}", { live.order { sim -> if (sim.chat(id, other.id)) null else "There’s no clear path to ${other.name}." } }, enabled = ready) + Box(Modifier.fillMaxWidth().height(hud.barH.dp), contentAlignment = Alignment.BottomCenter) { + Crossfade(active?.id, Modifier.fillMaxSize(), animationSpec = tween(MenuMotion.duration(MenuMotion.PAGE_MS, reduced)), + label = "orders") { id -> + if (id == null) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.BottomCenter) { + HudLine(SceneHud.hint(false, false, cast.size, false).ifEmpty { "Add NPCs to the scene to direct them." }, + Modifier.height(WifeTheme.touch), centered = true) + } + } else { + ActionBar(hud, slots, page, { page = it }, { slotEnabled(id, it) }, { act(id, it) }) + } + } } - RedButton(if (sending) "Tap an NPC…" else "Send to partner", { sending = !sending }, - enabled = ready && cast.size > 1) - RedButton("Free will", { live.order { sim -> sim.freeWill(id); null } }) } } + // a problem after loading (a prop without a surface, a file that wouldn't come): a fixed-width note on top + ProblemNote(status.takeIf { revealed }, Modifier.align(Alignment.TopCenter).padding(top = (SceneHud.TOP_H + 4f).dp)) } - val hint = if (npcCamera && selected != null) "Tap the floor to move." else "" - Text(snapshot.notice ?: hint, Modifier.fillMaxWidth().height(22.dp).padding(horizontal = 12.dp), color = Color.LightGray, - maxLines = 1, overflow = TextOverflow.Ellipsis) } choosingAnimation?.let { owner -> + // with a partner chosen, the two-person animations come first and play with them (solo ones still play alone) + val with = partnerId?.takeIf { it != owner } + val shownChoices = remember(choices, with) { if (with == null) choices else choices.sortedByDescending { it.participantCount == 2 } } + fun start(choice: AnimationChoice, mode: AnimationOrderMode) { + val order = PendingAnimation(owner, choice, mode) + if (choice.participantCount == 2) { if (with != null) schedule(order, with) else choosingPartner = order } + else schedule(order, null) + } AnimationBrowser( - choices, preview = null, onClose = { choosingAnimation = null }, notice = snapshot.notice, + shownChoices, preview = null, onClose = { choosingAnimation = null }, + notice = snapshot.notice ?: with?.let { "Two-person animations play with ${names[it]}." }, onPlay = { choice, mode -> if (mode == AnimationOrderMode.PLAY || mode == AnimationOrderMode.REPEAT) choosingAnimation = null - val order = PendingAnimation(owner, choice, mode) - if (choice.participantCount == 2) choosingPartner = order - else schedule(order, null) + start(choice, mode) }, + onPreview = { choice -> start(choice, AnimationOrderMode.PLAY) }, + partnerName = with?.let { names[it] }, + actorName = names[owner], ) } - choosingPartner?.let { order -> - val candidates = cast.filter { it.id != order.owner }.map { it.id to it.name } + val sayFor = rememberHeld(saying) + if (sayFor != null) { + val said = remember(words, sayFor) { words.sayings(sayFor) } + HudPick("Say", said.map { it to it }, saying != null, { saying = null }) { text -> + saying = null + live.order { sim -> sim.say(sayFor, text); null } + } + } + val chatFor = rememberHeld(chatting) + if (chatFor != null) { + HudPick("Chat with", cast.filter { it.id != chatFor }.map { it.id to it.name }, chatting != null, { chatting = null }) { other -> + chatting = null + chatWith(chatFor, other) + } + } + val pending = rememberHeld(choosingPartner) + if (pending != null) { + val candidates = cast.filter { it.id != pending.owner }.map { it.id to it.name } if (candidates.isEmpty()) { - ConfirmDialog("Add a second NPC to the scene to play this animation.", "OK", - { choosingPartner = null }, { choosingPartner = null }) + HudConfirm("Partner animation", "Add a second NPC to the scene to play this animation.", "OK", + choosingPartner != null, { choosingPartner = null }, { choosingPartner = null }) } else { - PickDialog("Choose a partner", candidates, null, { choosingPartner = null }) { partner -> + HudPick("Choose a partner", candidates, choosingPartner != null, { choosingPartner = null }) { other -> choosingPartner = null - schedule(order, partner) + schedule(pending, other) } } } - ConfirmDialog("End this scene?", "End scene", { ending = false }, { + SceneMenu(menu, { menu = false }, onSettings?.let { open -> { menu = false; open() } }, { menu = false; ending = true }) + HudConfirm("End scene", "End this scene and go back to the title?", "End scene", ending, { ending = false }, { live.command { it.endPartners() } partnerSounds.stopAll() onEnd() - }, visible = ending) + }) +} + +/** What a cast frame says someone is doing. */ +private fun doing(person: SceneSnapshot.PersonView, names: Map): String = + person.partner?.let { "With ${names[it]}" } ?: person.talkingWith?.let { "Talking to ${names[it]}" } ?: person.activity.description + +/** The action bar's words for using an object. */ +private fun useLabel(item: SceneObject): String = when (item) { + SceneObject.CHAIR -> "Sit in chair" + SceneObject.COUCH -> "Sit on couch" + SceneObject.BED -> "Rest on bed" + SceneObject.TABLE -> "Read a book" +} + +/** Whether the partner fallback's game emote [anim] is held (Dance) rather than played once (Wave, Bow...). */ +private fun emoteHeld(anim: Int): Boolean = + PartnerEmotes.ALL.firstOrNull { it.anim == anim }?.let { it.loop || EmotePlayability.heldByName(it.name) } ?: false + +/** The top bar: the place and the clock in a slate pill, the scene menu's gear at the other end, over a soft shade. */ +@Composable +private fun SceneTopBar(place: String, onMenu: () -> Unit, modifier: Modifier) { + val context = LocalContext.current + val h24 = remember(context) { android.text.format.DateFormat.is24HourFormat(context) } + var time by remember { mutableStateOf(clockNow(h24)) } + LaunchedEffect(h24) { while (true) { time = clockNow(h24); delay(15_000) } } + Box(modifier.height(SceneHud.TOP_H.dp).background(Brush.verticalGradient(listOf(Color(0x8C000000), Color.Transparent)))) { + Row(Modifier.fillMaxSize().padding(horizontal = SceneHud.MARGIN.dp), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween) { + val shape = RoundedCornerShape(50) + Row( + Modifier.weight(1f, fill = false).clip(shape).background(WifeTheme.slate).border(WifeTheme.trimWidth, WifeTheme.trimSoft, shape) + .padding(horizontal = WifeTheme.gapL, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapM), + ) { + Text(place, Modifier.weight(1f, fill = false), style = WifeTheme.headingStyle(), maxLines = 1, overflow = TextOverflow.Ellipsis) + // a fixed width: "12:59 PM" and "1:05 AM" take the same room + Text(time, Modifier.width(72.dp), style = WifeTheme.bodyStyle(WifeTheme.text), maxLines = 1, textAlign = TextAlign.End) + } + Spacer(Modifier.width(WifeTheme.gapS)) + HudIconButton(HudGlyph.GEAR, onMenu, "Scene menu") + } + } +} + +private fun clockNow(h24: Boolean): String { + val c = java.util.Calendar.getInstance() + return SceneHud.clock(c.get(java.util.Calendar.HOUR_OF_DAY), c.get(java.util.Calendar.MINUTE), h24) +} + +/** + * One NPC's party frame: their initial on a round plate, the name in gold over what they are doing; the controlled one in a + * gold edge with a glow, the partner in rose with "Partner" said. The whole frame is the touch target (taps control, or let go). + */ +@Composable +private fun CastFrame(name: String, doing: String, controlled: Boolean, partner: Boolean, onClick: () -> Unit, modifier: Modifier) { + val reduced = reduceMotion() + val ms = MenuMotion.duration(FrontMotion.GLOW_MS, reduced) + val edge by animateColorAsState(when { controlled -> WifeTheme.gold; partner -> PartnerRose; else -> WifeTheme.trimSoft }, tween(ms), label = "edge") + val lit by animateFloatAsState(if (controlled) 1f else 0f, tween(ms), label = "lit") + val shape = RoundedCornerShape(WifeTheme.buttonRadius) + Row( + modifier + .semantics { contentDescription = "$name, $doing" + if (partner) ", partner" else "" } + .drawBehind { + if (lit > 0f) drawRoundRect(WifeTheme.glow.copy(alpha = 0.22f * lit), cornerRadius = CornerRadius(WifeTheme.buttonRadius.toPx())) + } + .clip(shape) + .background(Brush.verticalGradient(listOf(WifeTheme.slate, WifeTheme.slateDeep))) + .border(if (controlled || partner) 2.dp else WifeTheme.trimWidth, edge, shape) + .warPress(sound = "select", onClick = onClick) + .padding(horizontal = WifeTheme.gapS), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapS), + ) { + Box( + Modifier.size(38.dp).clip(CircleShape).background(Brush.verticalGradient(listOf(WifeTheme.slateRaised, WifeTheme.slateDeep))) + .border(1.dp, edge, CircleShape), + contentAlignment = Alignment.Center, + ) { + Text(name.take(1).uppercase(), style = WifeTheme.headingStyle()) + } + Column(Modifier.weight(1f)) { + Text(name, style = frizStyle(WifeTheme.body, if (controlled) Color.White else WifeTheme.gold), maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(if (partner) "Partner · $doing" else doing, style = WifeTheme.captionStyle(if (partner) PartnerRose else WifeTheme.textDim), + maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } +} + +/** A line of help over the scene, on a slate pill so it reads over any room. */ +@Composable +private fun HudLine(text: String, modifier: Modifier = Modifier, centered: Boolean = false) { + val shape = RoundedCornerShape(50) + Box( + modifier.clip(shape).background(WifeTheme.slate).border(WifeTheme.trimWidth, WifeTheme.trimSoft, shape) + .padding(horizontal = WifeTheme.gapL, vertical = 6.dp), + contentAlignment = Alignment.Center, + ) { + Text(rememberHeld(text) ?: "", style = WifeTheme.bodyStyle(), maxLines = 1, overflow = TextOverflow.Ellipsis, + textAlign = if (centered) TextAlign.Center else TextAlign.Start) + } +} + +/** + * The action bar: [SceneHud.SLOTS] slots a page in [HudLayout.cols] x [HudLayout.rows] (empty places kept, so the slots never + * move), and the page button at its end (the game's action bar arrows: it turns the pages, and is dim with one page). + */ +@Composable +private fun ActionBar( + hud: HudLayout, + slots: List, + page: Int, + onPage: (Int) -> Unit, + enabled: (HudSlot) -> Boolean, + onSlot: (HudSlot) -> Unit, +) { + val pages = SceneHud.pages(slots.size) + val at = SceneHud.clampPage(page, slots.size) + val reduced = reduceMotion() + Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(SceneHud.GAP.dp), verticalAlignment = Alignment.Bottom) { + Crossfade(at, Modifier.weight(1f), animationSpec = tween(MenuMotion.duration(MenuMotion.PAGE_MS, reduced)), label = "page") { p -> + val shownSlots = SceneHud.page(slots, p) + Column(verticalArrangement = Arrangement.spacedBy(SceneHud.GAP.dp)) { + for (r in 0 until hud.rows) { + Row(horizontalArrangement = Arrangement.spacedBy(SceneHud.GAP.dp)) { + for (c in 0 until hud.cols) { + val slot = shownSlots.getOrNull(r * hud.cols + c) + if (slot == null) Spacer(Modifier.width(hud.slotW.dp).height(SceneHud.SLOT_H.dp)) + else key(slot.key) { ActionSlot(slot, enabled(slot), { onSlot(slot) }, Modifier.width(hud.slotW.dp)) } + } + } + } + } + } + PageButton(at, pages, { onPage((at + 1) % pages) }) + } +} + +/** One action-bar slot: a slate key with the gold trim, its words; lit gold while on (Walk), glowing while pressed. */ +@Composable +private fun ActionSlot(slot: HudSlot, enabled: Boolean, onClick: () -> Unit, modifier: Modifier) { + val play = LocalSounds.current + val source = remember { MutableInteractionSource() } + val pressed by source.collectIsPressedAsState() + val reduced = reduceMotion() + val glow by animateFloatAsState( + when { !enabled -> 0f; pressed -> 1f; slot.lit -> 0.75f; else -> 0f }, + tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced)), label = "slot", + ) + val sink by animateFloatAsState(MenuMotion.pressScale(pressed && enabled, reduced), tween(MenuMotion.duration(MenuMotion.PRESS_MS, reduced)), label = "press") + val gate = rememberClickGate() + Box( + modifier + .height(SceneHud.SLOT_H.dp) + .graphicsLayer { scaleX = sink; scaleY = sink } + .semantics { if (slot.lit) contentDescription = "${slot.label}, on" } + .clickable(source, null, enabled = enabled, role = Role.Button, onClick = { if (gate.pass()) { play("click"); onClick() } }) + .drawBehind { + val r = CornerRadius(WifeTheme.buttonRadius.toPx()) + val a = if (enabled) 0.94f else 0.5f + drawRoundRect(Brush.verticalGradient(listOf(WifeTheme.secondaryTop, WifeTheme.secondaryBottom)), cornerRadius = r, alpha = a) + if (glow > 0f) drawRoundRect( + Brush.radialGradient(listOf(WifeTheme.glow.copy(alpha = 0.38f * glow), Color.Transparent), + center = Offset(size.width / 2, size.height), radius = (size.width * 0.7f).coerceAtLeast(1f)), + cornerRadius = r, + ) + drawRoundRect(Brush.verticalGradient(listOf(Color(0x22FFFFFF), Color.Transparent), endY = size.height * 0.5f), cornerRadius = r) + val w = (1f + glow).dp.toPx() + val edge = if (enabled) WifeTheme.trim.copy(alpha = 0.7f + 0.3f * glow) else WifeTheme.trimSoft + drawRoundRect(edge, Offset(w / 2, w / 2), Size(size.width - w, size.height - w), r, style = Stroke(w)) + } + .padding(horizontal = 6.dp), + contentAlignment = Alignment.Center, + ) { + val color = when { + !enabled -> WowColors.grey + slot.lit || glow > 0.5f -> Color.White + else -> WifeTheme.gold + } + Text(slot.label, style = frizStyle(13.sp, color), textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis) + } +} + +/** The action bar's page button: "1/2" between two small chevrons; 48 dp; dim and still with one page. */ +@Composable +private fun PageButton(page: Int, pages: Int, onNext: () -> Unit) { + val many = pages > 1 + Column( + Modifier.width(SceneHud.PAGER_W.dp).height(SceneHud.SLOT_H.dp) + .semantics { contentDescription = "Action bar page ${page + 1} of $pages" } + .warPress(many, sound = "tab", onClick = onNext), + horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, + ) { + val tint = if (many) WifeTheme.gold else WifeTheme.trimSoft + Canvas(Modifier.width(14.dp).height(7.dp)) { + drawLine(tint, Offset(0f, size.height), Offset(size.width / 2, 0f), 1.6.dp.toPx()) + drawLine(tint, Offset(size.width / 2, 0f), Offset(size.width, size.height), 1.6.dp.toPx()) + } + Text("${page + 1}/$pages", style = WifeTheme.captionStyle(if (many) WifeTheme.text else WifeTheme.textDim), maxLines = 1) + Canvas(Modifier.width(14.dp).height(7.dp)) { + drawLine(tint, Offset(0f, 0f), Offset(size.width / 2, size.height), 1.6.dp.toPx()) + drawLine(tint, Offset(size.width / 2, size.height), Offset(size.width, 0f), 1.6.dp.toPx()) + } + } +} + +private enum class HudGlyph { GEAR, PLUS, MINUS } + +/** A round slate button with a gold glyph: 40 dp drawn, 48 dp to touch. */ +@Composable +private fun HudIconButton(glyph: HudGlyph, onClick: () -> Unit, description: String, repeatable: Boolean = false) { + Box( + Modifier.size(WifeTheme.touch).semantics { contentDescription = description } + .warPress(repeatable = repeatable, onClick = onClick), + contentAlignment = Alignment.Center, + ) { + Canvas(Modifier.size(40.dp)) { + val r = size.minDimension / 2 + drawCircle(Brush.verticalGradient(listOf(WifeTheme.secondaryTop, WifeTheme.secondaryBottom)), r) + drawCircle(WifeTheme.trim, r - 0.5.dp.toPx(), style = Stroke(1.dp.toPx())) + val k = r * 0.42f + val w = 2.dp.toPx() + when (glyph) { + HudGlyph.PLUS -> { + drawLine(WifeTheme.gold, Offset(center.x - k, center.y), Offset(center.x + k, center.y), w) + drawLine(WifeTheme.gold, Offset(center.x, center.y - k), Offset(center.x, center.y + k), w) + } + HudGlyph.MINUS -> drawLine(WifeTheme.gold, Offset(center.x - k, center.y), Offset(center.x + k, center.y), w) + HudGlyph.GEAR -> { + // eight teeth round a ring, a hole in the middle + val tooth = r * 0.16f + for (i in 0 until 8) rotate(i * 45f, center) { + drawRect(WifeTheme.gold, Offset(center.x - tooth / 2, center.y - r * 0.56f), Size(tooth, r * 0.2f)) + } + drawCircle(WifeTheme.gold, r * 0.4f, center, style = Stroke(r * 0.16f)) + } + } + } + } } /** The NPC camera's zoom buttons, faded in and out with it (the springs ease each step). */ @Composable private fun ZoomButtons(shown: Boolean, live: LiveScene, modifier: Modifier) { - AnimatedVisibility(shown, modifier, enter = fadeIn(), exit = fadeOut()) { - Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { - RoundIconButton(Face(glyph = WarIcons.PLUS), { live.camera.zoomBy(1.25f) }, size = 48.dp, description = "Zoom in") - RoundIconButton(Face(glyph = WarIcons.MINUS), { live.camera.zoomBy(0.8f) }, size = 48.dp, description = "Zoom out") + val reduced = reduceMotion() + AnimatedVisibility(shown, modifier, enter = fadeIn(tween(MenuMotion.duration(MenuMotion.WINDOW_IN_MS, reduced))), + exit = fadeOut(tween(MenuMotion.duration(MenuMotion.WINDOW_OUT_MS, reduced)))) { + Column(verticalArrangement = Arrangement.spacedBy(WifeTheme.gapXs)) { + HudIconButton(HudGlyph.PLUS, { live.camera.zoomBy(1.25f) }, "Zoom in", repeatable = true) + HudIconButton(HudGlyph.MINUS, { live.camera.zoomBy(0.8f) }, "Zoom out", repeatable = true) } } } @@ -543,15 +941,70 @@ private fun ZoomButtons(shown: Boolean, live: LiveScene, modifier: Modifier) { @Composable private fun ProblemNote(problem: String?, modifier: Modifier) { AnimatedVisibility(problem != null, modifier, enter = fadeIn(), exit = fadeOut()) { - Text(rememberHeld(problem) ?: "", Modifier.widthIn(max = 520.dp).background(Color(0xDD191719)).padding(8.dp), - color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis) + val shape = RoundedCornerShape(WifeTheme.buttonRadius) + Text(rememberHeld(problem) ?: "", Modifier.widthIn(max = 520.dp).clip(shape).background(WifeTheme.slate) + .border(WifeTheme.trimWidth, WifeTheme.danger.copy(alpha = 0.7f), shape).padding(horizontal = WifeTheme.gapM, vertical = WifeTheme.gapS), + style = WifeTheme.bodyStyle(), maxLines = 2, overflow = TextOverflow.Ellipsis) + } +} + +/** The scene menu (the top bar's gear): Resume, Options when the caller opens them, End scene. Fades in and out. */ +@Composable +private fun SceneMenu(visible: Boolean, onClose: () -> Unit, onOptions: (() -> Unit)?, onEnd: () -> Unit) { + Overlay(onClose, visible) { + WifeWindow("Scene", onClose, Modifier.widthIn(min = 260.dp, max = 340.dp).padding(WifeTheme.gapL)) { + Column(verticalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { + WifeButton("Resume", onClose, Modifier.fillMaxWidth(), kind = WifeButtonKind.PRIMARY, sound = "close") + if (onOptions != null) WifeButton("Options", onOptions, Modifier.fillMaxWidth(), sound = "open") + WifeButton("End scene", onEnd, Modifier.fillMaxWidth()) + } + } + } +} + +/** A question in a small [WifeWindow]: Cancel and [ok]. Fades in and out ([visible]). */ +@Composable +private fun HudConfirm(title: String, question: String, ok: String, visible: Boolean, onCancel: () -> Unit, onOk: () -> Unit) { + Overlay(onCancel, visible) { + WifeWindow(title, onCancel, Modifier.widthIn(max = 480.dp).padding(WifeTheme.gapL), footer = { + if (ok != "OK") WifeButton("Cancel", onCancel, Modifier.widthIn(min = 110.dp), sound = "close") + WifeButton(ok, onOk, Modifier.widthIn(min = 110.dp), kind = WifeButtonKind.PRIMARY, sound = "ok") + }) { + Text(question, style = WifeTheme.bodyStyle(), modifier = Modifier.padding(vertical = WifeTheme.gapXs)) + } + } +} + +/** A list of (id, words) to pick one from (Say, Chat with, a partner), in a [WifeWindow]; rows 48 dp or more. */ +@Composable +private fun HudPick(title: String, options: List>, visible: Boolean, onCancel: () -> Unit, onPick: (String) -> Unit) { + Overlay(onCancel, visible) { + WifeWindow(title, onCancel, Modifier.widthIn(min = 280.dp, max = 520.dp).heightIn(max = 520.dp).padding(WifeTheme.gapL)) { + val list = rememberLazyListState() + val keys = remember(options) { ListKeys.unique(options.map { it.first }) } + LazyColumn(Modifier.weight(1f, fill = false).warScrollbar(list), list, verticalArrangement = Arrangement.spacedBy(WifeTheme.gapXs)) { + if (options.isEmpty()) item { WifeNote("Nothing to choose.", Modifier.padding(WifeTheme.gapS)) } + items(options.size, key = { keys[it] }, contentType = { "row" }) { i -> + val (id, label) = options[i] + val shape = RoundedCornerShape(WifeTheme.buttonRadius) + Box( + Modifier.fillMaxWidth().heightIn(min = WifeTheme.touch).clip(shape).background(WifeTheme.slateRaised.copy(alpha = 0.6f)) + .border(WifeTheme.trimWidth, WifeTheme.trimSoft, shape).warPress { onPick(id) } + .padding(horizontal = WifeTheme.gapM, vertical = WifeTheme.gapS), + contentAlignment = Alignment.CenterStart, + ) { + Text(label, style = WifeTheme.labelStyle(), maxLines = 3, overflow = TextOverflow.Ellipsis) + } + } + } + } } } -/** The live screen's ground (behind the view while it starts, and under its bars). */ +/** The live screen's ground (behind the view while it starts). */ private val SceneGround = Color(0xFF191719) -/** Every cast tab is this wide: "Walking" and "Idle" never shift the row. */ -private val CAST_TAB_WIDTH = 188.dp +/** The partner's colour on the cast frames (the controlled one is gold). */ +private val PartnerRose = Color(0xFFE88AA8) /** Frames drawn after loading before the cover fades (the NPCs' skins are composed about one a frame). */ private const val REVEAL_FRAMES = 8L /** Radians two fingers must turn before a pinch turns the orbit too. */ @@ -569,27 +1022,29 @@ private fun BoxScope.SceneLoadingCover(visible: Boolean, name: String, status: S .pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } }, contentAlignment = Alignment.Center) { WarcraftLoadingArt(Modifier.matchParentSize()) - Column(Modifier.width(360.dp).background(Color(0xCC120E0C)).padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally) { - Text(name, style = frizStyle(18.sp), maxLines = 1, overflow = TextOverflow.Ellipsis) + Column(Modifier.widthIn(max = 360.dp).fillMaxWidth().padding(horizontal = WifeTheme.gapL).wifeSurface().padding(WifeTheme.gapL), + horizontalAlignment = Alignment.CenterHorizontally) { + Text(name, style = WifeTheme.titleStyle(), maxLines = 1, overflow = TextOverflow.Ellipsis) Box(Modifier.fillMaxWidth().height(48.dp), contentAlignment = Alignment.Center) { - Text(rememberHeld(status) ?: "Opening…", Modifier.fillMaxWidth(), color = Color.White, + Text(rememberHeld(status) ?: "Opening…", Modifier.fillMaxWidth(), style = WifeTheme.bodyStyle(), textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis) } - Box(Modifier.fillMaxWidth().height(6.dp).clipToBounds().background(Color(0x33FFFFFF))) { - if (progress != null) { - val p by animateFloatAsState(progress.coerceIn(0f, 1f), tween(250), label = "bar") - Box(Modifier.fillMaxHeight().fillMaxWidth(p).background(WowColors.gold)) - } else { + if (progress != null) { + val p by animateFloatAsState(progress.coerceIn(0f, 1f), tween(250), label = "bar") + WifeProgress(p) + } else { + Box(Modifier.fillMaxWidth().height(10.dp).clip(RoundedCornerShape(50)).clipToBounds().background(WifeTheme.track)) { val sweep = rememberInfiniteTransition(label = "sweep") val x by sweep.animateFloat(0f, 1f, infiniteRepeatable(tween(1200, easing = LinearEasing)), label = "x") Box(Modifier.fillMaxHeight().fillMaxWidth(0.3f).graphicsLayer { translationX = (x * 1.3f - 0.3f) * size.width / 0.3f } - .background(WowColors.gold)) + .background(WifeTheme.gold)) } } } } } +/** The animation library's front page (Import, Browse, Manage) in a [WifeWindow]; Browse opens the [AnimationBrowser]. */ @Composable fun SceneAnimationScreen( clips: List, @@ -604,16 +1059,23 @@ fun SceneAnimationScreen( ) { var browsing by remember { mutableStateOf(false) } BackHandler(!browsing, onBack) - BoxWithConstraints(Modifier.fillMaxSize().background(Color.Black), contentAlignment = Alignment.Center) { + Box(Modifier.fillMaxSize().background(Color.Black)) { WarcraftLoadingArt(Modifier.fillMaxSize()) - val layout = ChromeLayout.of(maxWidth.value, maxHeight.value) - WowWindow("Animation library", onBack, Modifier.width(layout.optionsW.dp).height(layout.optionsH.dp)) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) { - RedButton("Import WickedWhims", onImportWickedWhims, Modifier.weight(1f), textSize = 13.sp) - RedButton("Import rig and clips", onImport, Modifier.weight(1f), textSize = 13.sp) - RedButton("Browse animations", { browsing = true }, Modifier.weight(1f), textSize = 13.sp) + BoxWithConstraints(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.safeDrawing), contentAlignment = Alignment.Center) { + val layout = ChromeLayout.of(maxWidth.value, maxHeight.value) + WifeWindow("Animation library", onBack, Modifier.width(layout.optionsW.dp).heightIn(max = layout.optionsH.dp), + subtitle = "${clips.size} clip${if (clips.size == 1) "" else "s"}, ${pairs.count { it.enabled }} partner animation${if (pairs.count { it.enabled } == 1) "" else "s"}") { + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { + WifeButton("Browse animations", { browsing = true }, Modifier.fillMaxWidth(), kind = WifeButtonKind.PRIMARY, sound = "open") + WifeSectionHeader("Import") + WifeButton("Import WickedWhims", onImportWickedWhims, Modifier.fillMaxWidth()) + WifeButton("Import rig and clips", onImport, Modifier.fillMaxWidth()) + if (onManage != null) { + WifeSectionHeader("Library") + WifeButton("Manage library", onManage, Modifier.fillMaxWidth()) + } + } } - if (onManage != null) RedButton("Manage library", onManage, textSize = 13.sp) } } if (browsing) AnimationBrowser(remember(clips, pairs) { animationChoices(clips) + pairs.filter { it.enabled }.map { it.choice() } }, diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SpeechBubbles.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SpeechBubbles.kt new file mode 100644 index 00000000..575fb8b9 --- /dev/null +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/SpeechBubbles.kt @@ -0,0 +1,157 @@ +package com.logie.wifecraft.ui + +import androidx.compose.animation.core.animateFloatAsState +import androidx.compose.animation.core.tween +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.logie.wifecraft.simulation.SpeechLayout + +/** + * The speech bubbles' meeting point between the GL thread and the screen. The GL thread, each frame, writes every person's + * head (stage coordinates: [headAt]) and who is speaking ([speaking]), then [layout]s them with the frame's camera into a + * back buffer and [publish]es it (screen x, y, depth, shown: [SpeechLayout.STRIDE] a person); the screen reads the front + * one ([read]) in its draw phase (everyone is projected, speaking or not: the partner's marker uses it too). The screen + * writes the view's size ([width], [height], pixels). Nothing allocated per frame. + */ +class SpeechSpots(val count: Int) { + private val a = FloatArray(count * SpeechLayout.STRIDE) + private val b = FloatArray(count * SpeechLayout.STRIDE) + @Volatile private var front = a + private val hx = FloatArray(count) + private val hy = FloatArray(count) + private val hz = FloatArray(count) + /** GL thread: who has a line up now. */ + val speaking = BooleanArray(count) + @Volatile var width = 0f + @Volatile var height = 0f + + /** GL thread: person [index]'s head is at x, y, z (stage) this frame. */ + fun headAt(index: Int, x: Float, y: Float, z: Float) { + if (index !in 0 until count) return + hx[index] = x; hy[index] = y; hz[index] = z + } + + /** GL thread: everyone projected with this frame's camera and the bubbles chosen, then shown to the screen. */ + fun layout(ex: Float, ey: Float, ez: Float, ax: Float, ay: Float, az: Float, fov: Float) { + val buf = if (front === a) b else a + val w = width; val h = height + for (i in 0 until count) SpeechLayout.project(ex, ey, ez, ax, ay, az, fov, w, h, hx[i], hy[i], hz[i], buf, i * SpeechLayout.STRIDE) + SpeechLayout.choose(count, speaking, buf) + front = buf + } + + /** The screen: the last frame's layout (read it, don't keep it). */ + fun read(): FloatArray = front +} + +/** + * Over the 3D view: a speech bubble above each speaker the layout shows (the game's chat bubble: a dark rounded box with a + * light rim and a tail, the words in Friz in the front menus' pale ink, the speaker's name small and gold above them), faded + * in and out; and a small rose marker over the controlled NPC's partner ([marked]: their index, -1 none; rose as the cast + * frames mark the partner). [lines] holds each person's line now (null: none). Moved every frame in the + * draw phase only (no recomposition). + * Touches pass through to the view. + */ +@Composable +fun BoxScope.SpeechBubbles(spots: SpeechSpots, names: List, lines: List, marked: Int) { + var tick by remember { mutableLongStateOf(0L) } + val active = lines.any { it != null } || marked >= 0 + LaunchedEffect(active) { if (active) while (true) withFrameNanos { tick = it } } + for (i in 0 until spots.count) key(i) { + val text = lines.getOrNull(i) + // the last line, kept while the bubble fades out + val held = rememberHeld(text) ?: "" + val fade by animateFloatAsState(if (text != null) 1f else 0f, tween(if (text != null) 160 else 420), label = "bubble") + if (fade > 0f) { + Bubble(names.getOrElse(i) { "" }, held, Modifier.align(Alignment.TopStart).graphicsLayer { + tick // read each frame: the layer moves with the head + val buf = spots.read() + val o = i * SpeechLayout.STRIDE + val shown = buf[o + 3] == 1f + val lift = if (marked == i) MARK_LIFT.toPx() else 0f + val maxX = (spots.width - size.width).coerceAtLeast(0f) + translationX = (buf[o] - size.width / 2f).coerceIn(0f, maxX) + translationY = buf[o + 1] - size.height - lift + alpha = if (shown) fade else 0f + }) + } + } + val mark = marked + if (mark in 0 until spots.count) key("mark") { + Text("▼", Modifier.align(Alignment.TopStart).graphicsLayer { + tick + val buf = spots.read() + val o = mark * SpeechLayout.STRIDE + translationX = buf[o] - size.width / 2f + translationY = buf[o + 1] - size.height + alpha = if (buf[o + 2] > 0f) 1f else 0f + }, style = frizStyle(18.sp, PartnerMark)) + } +} + +/** One bubble: [name] small and gold over [text], on the dark box with its rim and a tail down to the head. */ +@Composable +private fun Bubble(name: String, text: String, modifier: Modifier) { + Box(modifier.widthIn(max = 240.dp).drawBehind { + val tail = TAIL.toPx() + val radius = 12.dp.toPx() + val rim = 1.2.dp.toPx() + val bodyH = this.size.height - tail + val bodyW = this.size.width + drawRoundRect(BubbleFill, Offset.Zero, Size(bodyW, bodyH), CornerRadius(radius)) + // the light from above, as the front menus' panels have + drawRoundRect(Brush.verticalGradient(listOf(Color(0x1AFFFFFF), Color.Transparent), endY = bodyH * 0.6f), Offset.Zero, Size(bodyW, bodyH), CornerRadius(radius)) + drawRoundRect(BubbleRim, Offset(rim / 2, rim / 2), Size(bodyW - rim, bodyH - rim), CornerRadius(radius), style = Stroke(rim)) + val mid = bodyW / 2f + val spike = Path().apply { + moveTo(mid - tail * 0.8f, bodyH - rim) + lineTo(mid + tail * 0.5f, bodyH - rim) + lineTo(mid - tail * 0.2f, bodyH + tail - rim) + close() + } + drawPath(spike, BubbleFill) + drawLine(BubbleRim, Offset(mid - tail * 0.8f, bodyH - rim / 2), Offset(mid - tail * 0.2f, bodyH + tail - rim), rim) + drawLine(BubbleRim, Offset(mid + tail * 0.5f, bodyH - rim / 2), Offset(mid - tail * 0.2f, bodyH + tail - rim), rim) + }.padding(start = 12.dp, end = 12.dp, top = 6.dp, bottom = 7.dp + TAIL)) { + Column { + if (name.isNotEmpty()) Text(name, style = frizStyle(WifeTheme.caption, WifeTheme.gold), maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(text, style = frizStyle(13.sp, WifeTheme.text).copy(lineHeight = 17.sp), textAlign = TextAlign.Start, maxLines = 4, + overflow = TextOverflow.Ellipsis) + } + } +} + +private val TAIL = 9.dp +/** How much higher a bubble sits over the partner, above its marker. */ +private val MARK_LIFT = 18.dp +/** The game's chat bubble: near-black, a little see-through, its rim the menus' gold trim softened. */ +private val BubbleFill = Color(0xE00B0E13) +private val BubbleRim = WifeTheme.trim.copy(alpha = 0.75f) +private val PartnerMark = Color(0xFFE88AA8) diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/TitleScreen.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/TitleScreen.kt index fcbf32a0..83492beb 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/TitleScreen.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/TitleScreen.kt @@ -1,47 +1,65 @@ package com.logie.wifecraft.ui +import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.LinearEasing +import androidx.compose.animation.core.RepeatMode +import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.infiniteRepeatable +import androidx.compose.animation.core.rememberInfiniteTransition +import androidx.compose.animation.core.tween +import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.State import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember -import androidx.compose.animation.core.Animatable -import androidx.compose.animation.core.tween -import androidx.compose.ui.graphics.ImageBitmap -import androidx.compose.ui.graphics.asImageBitmap -import androidx.compose.ui.graphics.graphicsLayer -import androidx.compose.ui.platform.LocalContext -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext import androidx.compose.ui.Alignment import androidx.compose.ui.BiasAlignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.res.painterResource +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.logie.wifecraft.BuildConfig import com.logie.wifecraft.R +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +/** + * The title: the backdrop breathing slowly with motes rising over it ([WifecraftMenuBackdrop]), the crest and the name, and + * the menu on a slate panel: the main action in the game's red (Choose Scene, or Gather the Files until the files are here), + * Options and Updates. Down the left on a wide screen, centred on a narrow one ([FrontLayout.title]); it scrolls rather than + * clip on a short one. + */ @Composable fun TitleScreen( filesReady: Boolean, @@ -53,46 +71,97 @@ fun TitleScreen( onUpdates: () -> Unit, ) { BoxWithConstraints(Modifier.fillMaxSize().background(Color.Black)) { - val layout = ChromeLayout.of(maxWidth.value, maxHeight.value) - val short = maxHeight < 520.dp + val l = FrontLayout.title(maxWidth.value, maxHeight.value) WifecraftMenuBackdrop(Modifier.fillMaxSize(), BiasAlignment(0.6f, -0.4f)) - // the menu comes in with the screen (a short fade and rise), once - val enter = rememberEnter(MenuMotion.WINDOW_IN_MS + 40) Box( Modifier.fillMaxSize().background( - Brush.horizontalGradient(0f to Color(0xD0080418), 0.42f to Color(0x80080418), 0.62f to Color.Transparent), + if (l.centered) Brush.verticalGradient(0f to Color(0x55060A10), 0.45f to Color(0x99060A10), 1f to Color(0xE6060A10)) + else Brush.horizontalGradient(0f to Color(0xE0060A10), 0.42f to Color(0x8C060A10), 0.68f to Color.Transparent), ), ) - Column( - Modifier.padding(start = 40.dp, top = if (short) 20.dp else 32.dp, bottom = 16.dp, end = 16.dp).fillMaxSize() - .graphicsLayer { alpha = enter.value; translationY = (1f - enter.value) * 8.dp.toPx() }, - ) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) { - MenuPicture(R.drawable.wc_emblem, Modifier.size(if (short) 56.dp else 74.dp).clip(CircleShape), ContentScale.Fit) - Text("Wifecraft", style = morpheusStyle(if (short) 40.sp else 50.sp)) + // the menu comes in with the screen (a short fade and rise), once + val enter = rememberEnter(MenuMotion.WINDOW_IN_MS + 80) + val minHeight = maxHeight + Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) { + Column( + Modifier.fillMaxWidth().heightIn(min = minHeight) + .padding(horizontal = l.padH.dp).padding(top = l.padTop.dp, bottom = 48.dp) + .graphicsLayer { alpha = enter.value; translationY = (1f - enter.value) * 12.dp.toPx() }, + verticalArrangement = Arrangement.spacedBy(WifeTheme.gapM, Alignment.CenterVertically), + horizontalAlignment = if (l.centered) Alignment.CenterHorizontally else Alignment.Start, + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapM)) { + MenuPicture(R.drawable.wc_emblem, Modifier.size(l.crestDp.dp).clip(CircleShape), ContentScale.Fit) + Column { + Text("Wifecraft", style = WifeTheme.displayStyle(l.titleSp.sp), maxLines = 1) + Text("A Warcraft dating sim", style = WifeTheme.captionStyle(WifeTheme.text), maxLines = 1) + } + } + WifePanel(Modifier.width((l.buttonW + 2 * 16f).dp)) { + Column(verticalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { + if (filesReady) WifeButton("Choose Scene", onChooseScene, Modifier.fillMaxWidth(), kind = WifeButtonKind.PRIMARY, sound = "ok") + else WifeButton("Gather the Files", onGather, Modifier.fillMaxWidth(), kind = WifeButtonKind.PRIMARY, sound = "ok") + // the windows play the game's open sound themselves + WifeButton("Options", onOptions, Modifier.fillMaxWidth(), sound = "") + WifeButton(if (updateTitle != null) "Updates • New" else "Updates", onUpdates, Modifier.fillMaxWidth(), sound = "") + } + } + if (!filesReady) WifeNote( + "Download the game's files to create and play with NPCs. Allow about $downloadSize.", + Modifier.widthIn(max = l.buttonW.dp + 32.dp), + WifeTheme.text, + ) } - Spacer(Modifier.height(if (short) 14.dp else 26.dp)) - val buttons = listOf( - (if (filesReady) "Choose Scene" else "Gather the Files") to (if (filesReady) onChooseScene else onGather), - "Options" to onOptions, - "Updates" to onUpdates, - ) - RedStack(buttons.map { StackButton(it, true) }, { it.first }, layout.titleCols, 260.dp, { it.second() }) - if (!filesReady) Text( - "Download the game files to create and play with NPCs. Allow about $downloadSize.", - style = frizStyle(12.sp, Color.White), modifier = Modifier.padding(top = 8.dp).widthIn(max = 540.dp), - ) } - Column(Modifier.align(Alignment.BottomEnd).padding(12.dp), horizontalAlignment = Alignment.End) { - if (updateTitle != null) Text("$updateTitle is out: Updates installs it.", style = frizStyle(11.sp, Color.White)) - Text("Version ${BuildConfig.VERSION_NAME}", style = frizStyle(11.sp)) + Column(Modifier.align(Alignment.BottomEnd).padding(WifeTheme.gapM), horizontalAlignment = Alignment.End) { + if (updateTitle != null) Text("$updateTitle is out: Updates installs it.", style = WifeTheme.captionStyle(WifeTheme.text), textAlign = TextAlign.End) + Text("Version ${BuildConfig.VERSION_NAME}", style = WifeTheme.captionStyle()) } } } +/** + * The menus' backdrop: the header picture breathing slowly (a gentle scale and pan, FrontMotion.drift) with pale motes rising + * over it at their own pace (the parallax: two layers moving differently), and a vignette. Still under reduced motion. The + * animation is read only where it is drawn (a layer's transform, one small canvas), so it redraws, never recomposes. + */ @Composable -internal fun WifecraftMenuBackdrop(modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center) { - MenuPicture(R.drawable.wc_header, modifier, ContentScale.Crop, alignment) +internal fun WifecraftMenuBackdrop(modifier: Modifier = Modifier, alignment: Alignment = Alignment.Center, motes: Boolean = true) { + val reduced = reduceMotion() + val drift: State + val rise: State + if (reduced) { + drift = remember { mutableFloatStateOf(0f) } + rise = remember { mutableFloatStateOf(0.3f) } + } else { + val t = rememberInfiniteTransition(label = "backdrop") + drift = t.animateFloat(0f, 1f, infiniteRepeatable(tween(FrontMotion.DRIFT_MS, easing = LinearEasing), RepeatMode.Restart), label = "drift") + rise = t.animateFloat(0f, 1f, infiniteRepeatable(tween(FrontMotion.DRIFT_MS / 2, easing = LinearEasing), RepeatMode.Restart), label = "motes") + } + Box(modifier) { + MenuPicture( + R.drawable.wc_header, + Modifier.fillMaxSize().graphicsLayer { + val (s, px, py) = FrontMotion.drift(drift.value, reduced) + scaleX = s; scaleY = s + translationX = px * size.width; translationY = py * size.height + }, + ContentScale.Crop, alignment, + ) + if (motes) Canvas(Modifier.fillMaxSize()) { + val p = rise.value + val r = 1.6.dp.toPx() + for (i in 0 until FrontMotion.MOTES) { + val (x, y, a) = FrontMotion.mote(i, p) + if (a <= 0.01f) continue + val c = Offset(x * size.width, y * size.height) + drawCircle(Color(0xFFFFE2A0).copy(alpha = a * 0.35f), r * 3f, c) + drawCircle(Color(0xFFFFF1C8).copy(alpha = a), r, c) + } + } + // the vignette: the edges darker, the eye kept on the menu + Box(Modifier.fillMaxSize().background(Brush.radialGradient(0.55f to Color.Transparent, 1f to Color(0x99000000)))) + } } /** @@ -123,7 +192,7 @@ private fun MenuPicture(id: Int, modifier: Modifier, scale: ContentScale, alignm } } -/** The first launch's loading screen: what's fetched, the bar, and the choices about it. */ +/** The first launch's gathering screen: the splash, and on a slate panel what's fetched, the bar, and the choices about it. */ @Composable fun GatherScreen( progress: com.logie.wifecraft.data.GameFiles.Progress, @@ -134,53 +203,56 @@ fun GatherScreen( onPause: () -> Unit, onBack: () -> Unit, ) { - val art = LocalArt.current - Box(Modifier.fillMaxSize().background(Color.Black)) { + BoxWithConstraints(Modifier.fillMaxSize().background(Color.Black)) { + val screenW = maxWidth + val screenH = maxHeight MenuPicture(R.drawable.wc_splash, Modifier.fillMaxSize(), ContentScale.Crop) - Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.55f to Color.Transparent, 1f to Color(0xE0000000)))) - Column(Modifier.align(Alignment.TopEnd).padding(16.dp), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.spacedBy(6.dp)) { - // one button that changes its words (two would each let a quick double tap through: Start, then Pause at once) - WowButton(if (progress.running) "Pause" else if (progress.done > 0) "Resume" else "Start", if (progress.running) onPause else onStart, width = 140.dp, height = 40.dp) - WowButton("Back", onBack, width = 140.dp, height = 40.dp) - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 4.dp)) { - androidx.compose.material3.Checkbox(wifiOnly, onWifiOnly, colors = goldCheckbox()) - Text("Wi-Fi only", style = frizStyle(13.sp)) - } - } - Column(Modifier.align(Alignment.BottomCenter).padding(bottom = 14.dp), horizontalAlignment = Alignment.CenterHorizontally) { - val mb = { b: Long -> if (b >= 1_000_000_000L) "%.1f GB".format(b / 1e9) else "%.0f MB".format(b / 1e6) } - // the total is an estimate until the creator's files are all here (wago.tools gives no sizes ahead) - val of = (if (progress.estimated) "about " else "") + mb(progress.total) - val count = "${progress.files} of ${progress.filesTotal}${if (progress.filesExact) "" else "+"} files" - val status = when { - progress.error != null -> "Stopped: ${progress.error}. Resume tries again." - progress.waitingForWifi -> "Waiting for Wi-Fi (or turn Wi-Fi only off)." - progress.finished -> "Everything is here." - progress.running -> "Gathering ${packLabels.firstOrNull { it.first == progress.current }?.second ?: "the game's files"}… $count, ${mb(progress.done)} of $of" - else -> "$count, ${mb(progress.done)} of $of on the phone" - } - Text(status, style = frizStyle(15.sp)) - if (progress.running) Text( - if (progress.parallel < progress.parallelCeiling) "slowed to ${progress.parallel}: wago.tools asked for less" else "${progress.parallel} at once", - style = frizStyle(12.sp, if (progress.parallel < progress.parallelCeiling) Color(0xFFFFD060) else Color.White), - ) - if (progress.failed.isNotEmpty() && !progress.running) { - Spacer(Modifier.height(4.dp)) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { - Text("${progress.failed.size} ${if (progress.failed.size == 1) "file" else "files"} could not be fetched.", style = frizStyle(13.sp, Color(0xFFFF6060))) - WowButton("Retry", onStart, width = 112.dp, height = 36.dp) - } - } - Spacer(Modifier.height(6.dp)) - LoadingBar(if (progress.total > 0) progress.done.toFloat() / progress.total else 0f, Modifier.width(560.dp).height(52.dp)) - Spacer(Modifier.height(4.dp)) - Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) { - for ((key, label) in packLabels) { - val done = key in progress.complete - Text((if (done) "✓ " else "") + label, style = frizStyle(11.sp, if (done) Color(0xFF7CFC7C) else Color.White)) + Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0.45f to Color.Transparent, 1f to Color(0xE6000000)))) + val panelW = minOf(600.dp, screenW - 32.dp).coerceAtLeast(0.dp) + Box(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), contentAlignment = Alignment.BottomCenter) { + Box(Modifier.heightIn(min = (screenH - 32.dp).coerceAtLeast(0.dp)), contentAlignment = Alignment.BottomCenter) { + WifePanel(Modifier.width(panelW)) { + val mb = { b: Long -> if (b >= 1_000_000_000L) "%.1f GB".format(b / 1e9) else "%.0f MB".format(b / 1e6) } + // the total is an estimate until the creator's files are all here (wago.tools gives no sizes ahead) + val of = (if (progress.estimated) "about " else "") + mb(progress.total) + val count = "${progress.files} of ${progress.filesTotal}${if (progress.filesExact) "" else "+"} files" + val status = when { + progress.error != null -> "Stopped: ${progress.error}. Resume tries again." + progress.waitingForWifi -> "Waiting for Wi-Fi (or turn Wi-Fi only off)." + progress.finished -> "Everything is here." + progress.running -> "Gathering ${packLabels.firstOrNull { it.first == progress.current }?.second ?: "the game's files"}… $count, ${mb(progress.done)} of $of" + else -> "$count, ${mb(progress.done)} of $of on the phone" + } + Text("Gathering the Files", style = WifeTheme.titleStyle(), maxLines = 1) + WifeDivider(Modifier.padding(vertical = WifeTheme.gapXs)) + // two lines kept for the status whatever it says: the bar and the buttons never move under the finger + Text(status, style = WifeTheme.bodyStyle(), minLines = 2, maxLines = 3) + Text( + if (!progress.running) "" else if (progress.parallel < progress.parallelCeiling) "Slowed to ${progress.parallel}: wago.tools asked for less" else "${progress.parallel} at once", + style = WifeTheme.captionStyle(if (progress.parallel < progress.parallelCeiling) Color(0xFFFFD060) else WifeTheme.textDim), maxLines = 1, + ) + WifeGap() + WifeProgress(if (progress.total > 0) progress.done.toFloat() / progress.total else 0f) + WifeGap(WifeTheme.gapXs) + Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapM)) { + for ((key, label) in packLabels) { + val done = key in progress.complete + Text((if (done) "✓ " else "") + label, style = WifeTheme.captionStyle(if (done) WifeTheme.good else WifeTheme.text), maxLines = 1) + } + } + if (progress.failed.isNotEmpty() && !progress.running) { + Text("${progress.failed.size} ${if (progress.failed.size == 1) "file" else "files"} could not be fetched: Resume tries them again.", + style = WifeTheme.captionStyle(WifeTheme.danger), modifier = Modifier.padding(top = WifeTheme.gapXs)) + } + WifeSwitchRow("Wi-Fi only", wifiOnly, onWifiOnly, detail = "A look's own files still come as it is shown") + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapS)) { + WifeButton("Back", onBack, Modifier.weight(1f), sound = "close") + // one button that changes its words (two would each let a quick double tap through: Start, then Pause at once) + WifeButton(if (progress.running) "Pause" else if (progress.done > 0) "Resume" else "Start", + if (progress.running) onPause else onStart, Modifier.weight(1f), kind = WifeButtonKind.PRIMARY) + } } } - if (art == null || !art.ready) Spacer(Modifier.height(0.dp)) } } } diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WarWidgets.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WarWidgets.kt index ef7615c8..f4dfc02a 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WarWidgets.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WarWidgets.kt @@ -306,66 +306,6 @@ fun Badge(text: String, modifier: Modifier = Modifier) { ) { Text(text, style = warText(10.sp, War.brown), maxLines = 1) } } -/** - * A category tab of the catalogue bar: a round item icon in the talent tree's ring (grey; gold and raised, a little larger - * and glowing when [chosen]), its name under it, its count on the rim. - */ -@Composable -fun CategoryTab(tab: CatalogueTab, chosen: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, showCount: Boolean = true) { - val war = LocalWar.current - val rise by animateFloatAsState(if (chosen) WarSize.TAB_RAISE else 0f, tween(160), label = "rise") - val grow by animateFloatAsState(if (chosen) WarSize.TAB_CHOSEN_SCALE else 1f, tween(160), label = "grow") - Column(modifier.width(72.dp), horizontalAlignment = Alignment.CenterHorizontally) { - Box( - Modifier.padding(top = WarSize.TAB_RAISE.dp).offset(y = (-rise).dp).size(WarSize.TAB.dp) - .graphicsLayer { scaleX = grow; scaleY = grow } - .semantics { contentDescription = tab.label } - .warPress(onClick = onClick), - ) { - Canvas(Modifier.matchParentSize()) { - val r = size.minDimension / 2; val c = center - if (chosen) war?.piece("housing-layout-room-orb-ring-active")?.let { g -> val gr = r * 1.45f; drawWar(g, c.x - gr, c.y - gr + 3.dp.toPx(), 2 * gr, 2 * gr, 0.9f) } - drawCircle(Color(WarPalette.SHADOW), r, c + Offset(0f, (if (chosen) 5 else 2).dp.toPx())) - val disc = war?.piece("common-radiobutton-circle") - if (disc != null) drawWar(disc, c.x - r, c.y - r, 2 * r, 2 * r) else drawCircle(War.woodDark, r, c) - val img = war?.icon(tab.icon) - if (img != null) drawCircled(img, c.x, c.y, 2 * r * 0.74f) else drawGlyphFor(tab.icon, c.x, c.y, 2 * r * 0.52f) - val ring = war?.piece(if (chosen) "talents-node-circle-yellow" else "talents-node-circle-gray") - val rr = r * 1.12f - if (ring != null) drawWar(ring, c.x - rr, c.y - rr, 2 * rr, 2 * rr) - else drawCircle(if (chosen) War.gold else War.muted, r, c, style = Stroke(2.5.dp.toPx())) - } - if (showCount && tab.count > 0) Badge(compactCount(tab.count), Modifier.align(Alignment.TopEnd).offset(x = 8.dp, y = (-4).dp)) - } - Text(tab.label, style = warText(11.sp, if (chosen) War.gold else War.ink, true), maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.padding(top = 4.dp)) - } -} - -/** 48,212 -> "48k"; under 10,000 as it is. */ -fun compactCount(n: Int): String = if (n >= 10_000) "${n / 1000}k" else "%,d".format(n) - -/** A chip of the category row: a cream pill (deep parchment with a gold edge when [on]), its icon, its name and count. */ -@Composable -fun Chip(label: String, count: Int?, on: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier, icon: String? = null) { - val war = LocalWar.current - val shape = RoundedCornerShape(50) - Row( - modifier.height(WarSize.CHIP_H.dp).padding(vertical = 4.dp).shadow(2.dp, shape).clip(shape) - .background(if (on) War.parchmentDeep else War.cream).border(if (on) 2.dp else 1.dp, if (on) War.gold else War.edge, shape) - .warPress(onClick = onClick).padding(start = if (icon != null) 6.dp else 14.dp, end = 14.dp), - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - if (icon != null) Canvas(Modifier.size(28.dp)) { - val img = war?.icon(icon) - if (img != null) drawCircled(img, center.x, center.y, size.minDimension) - else { drawCircle(War.woodDark, size.minDimension / 2); drawGlyphFor(icon, center.x, center.y, size.minDimension * 0.62f) } - } - Text(label, style = warText(13.sp), maxLines = 1) - if (count != null) Text("%,d".format(count), style = warText(11.sp, War.brownSoft), maxLines = 1) - } -} - /** A big friendly button: a rounded wood pill with gold words (red-brown for [danger]), an optional glyph before them. */ @Composable fun PillButton(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, danger: Boolean = false, glyph: String? = null, height: Dp = 48.dp) { @@ -390,62 +330,6 @@ fun PillButton(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, } } -/** An on/off switch: an amber track with the radio button's gold dot (a grey disc when off), its label after it. */ -@Composable -fun WarToggle(label: String, on: Boolean, onChange: (Boolean) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, dark: Boolean = false) { - val war = LocalWar.current - val at by animateFloatAsState(if (on) 1f else 0f, tween(140), label = "toggle") - Row( - modifier.heightIn(min = 48.dp).warPress(enabled) { onChange(!on) }, - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - Canvas(Modifier.width(56.dp).height(32.dp)) { - val h = size.height - drawRoundRect(if (on) War.amber else Color(0xFFBFA06A), cornerRadius = CornerRadius(h / 2), alpha = if (enabled) 1f else 0.5f) - drawRoundRect(War.woodDark, cornerRadius = CornerRadius(h / 2), style = Stroke(1.2.dp.toPx())) - val k = 28.dp.toPx(); val x = k / 2 + 2.dp.toPx() + (size.width - k - 4.dp.toPx()) * at - val knob = war?.piece(if (on) "common-radiobutton-dot" else "common-radiobutton-circle") - if (knob != null) drawWar(knob, x - k / 2, h / 2 - k / 2, k, k) else drawCircle(if (on) War.gold else War.muted, k / 2, Offset(x, h / 2)) - } - Text(label, style = warText(14.sp, if (dark) War.ink else War.brown, dark), maxLines = 2) - } -} - -/** - * A slider on parchment: an amber filled track, the radio button's gold dot as its knob. [value] in [range]; drags report - * [onChange], letting go [onFinished]. 48 dp high to touch. - */ -@Composable -fun WarSlider(value: Float, onChange: (Float) -> Unit, range: ClosedFloatingPointRange, modifier: Modifier = Modifier, enabled: Boolean = true, onFinished: () -> Unit = {}) { - val war = LocalWar.current - val change by rememberUpdatedState(onChange) - val finish by rememberUpdatedState(onFinished) - val on by rememberUpdatedState(enabled) - val span = (range.endInclusive - range.start).takeIf { it > 0f } ?: 1f - val frac = ((value - range.start) / span).coerceIn(0f, 1f) - fun at(x: Float, w: Float, knob: Float) = range.start + ((x - knob / 2) / (w - knob)).coerceIn(0f, 1f) * span - Canvas( - modifier.fillMaxWidth().height(48.dp) - .pointerInput(range) { - detectTapGestures { o -> if (on) { change(at(o.x, size.width.toFloat(), 26.dp.toPx())); finish() } } - } - .pointerInput(range) { - detectHorizontalDragGestures(onDragEnd = { if (on) finish() }, onDragCancel = { if (on) finish() }) { ch, _ -> - if (on) { ch.consume(); change(at(ch.position.x, size.width.toFloat(), 26.dp.toPx())) } - } - }, - ) { - val k = 26.dp.toPx(); val th = 8.dp.toPx(); val y = size.height / 2 - val x0 = k / 2; val w = size.width - k - drawRoundRect(Color(0xFFBFA06A), Offset(x0, y - th / 2), Size(w, th), CornerRadius(th / 2)) - drawRoundRect(War.amber, Offset(x0, y - th / 2), Size(w * frac, th), CornerRadius(th / 2), alpha = if (enabled) 1f else 0.5f) - val kx = x0 + w * frac - drawCircle(Color(WarPalette.SHADOW), k / 2, Offset(kx, y + 2.dp.toPx())) - val dot = war?.piece("common-radiobutton-dot") - if (dot != null) drawWar(dot, kx - k / 2, y - k / 2, k, k, if (enabled) 1f else 0.5f) else drawCircle(War.gold, k / 2, Offset(kx, y)) - } -} - /** A cream field on parchment: its label above it, the words in deep brown, a gold edge while typing. */ @Composable fun WarField( @@ -479,105 +363,6 @@ fun WarField( } } -/** A number typed on parchment: used when it reads as one and Done is pressed or the field is left. */ -@Composable -fun WarNumberField(label: String, value: Float, modifier: Modifier = Modifier, decimals: Int = 2, enabled: Boolean = true, onValue: (Float) -> Unit) { - var text by remember(value) { mutableStateOf(showNumber(value, decimals)) } - fun use() { readNumber(text)?.let { if (it != value) onValue(it) } ?: run { text = showNumber(value, decimals) } } - WarField( - text, { text = it.take(12) }, "", modifier, label = label, enabled = enabled, - keyboard = KeyboardOptions(keyboardType = KeyboardType.Decimal, imeAction = ImeAction.Done), - actions = KeyboardActions(onDone = { use() }), - onFocus = { f -> if (!f) use() }, - ) -} - -/** The search box: the magnifying glass, the words, Clear. On the dark bar: cream on warm glass. */ -@Composable -fun WarSearch(value: String, onChange: (String) -> Unit, hint: String, onClear: () -> Unit, modifier: Modifier = Modifier) { - val war = LocalWar.current - val shape = RoundedCornerShape(50) - Row( - modifier.height(48.dp).clip(shape).background(War.cream).border(1.5.dp, War.goldSoft, shape).padding(start = 12.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Canvas(Modifier.size(22.dp)) { - val img = war?.piece(WarIcons.SEARCH) - if (img != null) drawFitted(img, center.x, center.y, size.minDimension) else drawGlyph(WarGlyph.SEARCH, center.x, center.y, size.minDimension, War.brown) - } - Box(Modifier.weight(1f).padding(horizontal = 8.dp)) { - if (value.isEmpty()) Text(hint, style = warText(14.sp, War.muted), maxLines = 1) - BasicTextField(value, onChange, singleLine = true, textStyle = warText(15.sp), cursorBrush = SolidColor(War.brown), modifier = Modifier.fillMaxWidth()) - } - if (value.isNotEmpty()) RoundIconButton(Face(glyph = WarIcons.CLOSE), onClear, size = 48.dp, description = "Clear") - } -} - -// ------------------------------------------------------------------------------------------------ cards - -/** - * A picture card (the Sims' catalogue card): the decor chest's frame (gold when [armed]), the picture rounded inside it - * (or the name, or an initial, until it is drawn), the star for favourites at its corner (48 dp to touch), the name under it. - */ -@Composable -fun ItemCard( - name: AnnotatedString, - picture: ImageBitmap?, - size: Dp, - armed: Boolean, - favourite: Boolean, - onClick: () -> Unit, - onFavourite: (() -> Unit)?, - modifier: Modifier = Modifier, - placeholder: String = name.text.take(1).uppercase(), - badge: String? = null, - /** On parchment (the Library window): the name in deep brown instead of cream. */ - onLight: Boolean = false, - enabled: Boolean = true, - selection: Boolean? = null, -) { - val war = LocalWar.current - Column(modifier.width(size), horizontalAlignment = Alignment.CenterHorizontally) { - Box(Modifier.size(size).semantics { - contentDescription = name.text - if (selection != null) selected = selection - if (enabled) onClick { onClick(); true } else disabled() - }.warPress(enabled, onClick = onClick)) { - Canvas(Modifier.matchParentSize()) { - val s = this.size.width - drawRoundRect(Color(WarPalette.SHADOW), Offset(0f, 3.dp.toPx()), this.size, CornerRadius(16.dp.toPx())) - val frame = war?.piece(if (armed) "house-chest-list-item-active" else "house-chest-list-item-default") - if (frame != null) drawWar(frame, 0f, 0f, s, s) - else drawRoundRect(War.woodDark, cornerRadius = CornerRadius(16.dp.toPx())) - val inset = s * 0.085f; val r = 11.dp.toPx() - if (picture != null) { - val p = roundPath(inset, inset, s - inset, s - inset, r) - clipPath(p) { - drawRect(Color(0xFF2C1E14), Offset(inset, inset), Size(s - 2 * inset, s - 2 * inset)) - // the picture at its own aspect, centred - val k = minOf((s - 2 * inset) / picture.width, (s - 2 * inset) / picture.height) - drawWar(picture, (s - picture.width * k) / 2, (s - picture.height * k) / 2, picture.width * k, picture.height * k) - } - } - drawRoundRect(if (armed) War.gold else Color(0xC8785A32), Offset(inset, inset), Size(s - 2 * inset, s - 2 * inset), CornerRadius(r), - style = Stroke((if (armed) 2 else 1).dp.toPx())) - } - if (picture == null) Text(placeholder, style = warText(if (placeholder.length > 2) 11.sp else 28.sp, War.muted, true), textAlign = TextAlign.Center, maxLines = 4, - modifier = Modifier.align(Alignment.Center).padding(10.dp)) - if (onFavourite != null) Box(Modifier.align(Alignment.TopEnd).size(48.dp).warPress(onClick = onFavourite), contentAlignment = Alignment.TopEnd) { - Canvas(Modifier.padding(7.dp).size(22.dp)) { - val star = war?.piece(if (favourite) WarIcons.STAR else WarIcons.STAR_OFF) - if (star != null) drawFitted(star, center.x, center.y, this.size.minDimension) - else drawGlyph(WarGlyph.STAR, center.x, center.y, this.size.minDimension, if (favourite) War.gold else War.muted) - } - } - if (badge != null) Badge(badge, Modifier.align(Alignment.BottomEnd).padding(6.dp)) - } - Text(name, style = if (onLight) warText(12.sp, if (armed) War.wood else War.brown) else warText(11.5.sp, if (armed) War.gold else War.ink, true), maxLines = 2, overflow = TextOverflow.Ellipsis, - textAlign = TextAlign.Center, modifier = Modifier.padding(top = 4.dp)) - } -} - // ------------------------------------------------------------------------------------------------ panels /** @@ -604,40 +389,6 @@ fun BookPage(modifier: Modifier = Modifier, ribbon: Boolean = true, content: @Co ) } -/** A page's header: a small grey line over a name in Morpheus, an optional line under it, a thin rule. */ -@Composable -fun BookHeader(over: String?, title: String, under: String? = null, actions: @Composable RowScope.() -> Unit = {}) { - Column(Modifier.fillMaxWidth()) { - Row(verticalAlignment = Alignment.CenterVertically) { - Column(Modifier.weight(1f)) { - if (over != null) Text(over, style = warText(12.sp, War.brownSoft), maxLines = 1) - Text(title, style = warTitle(22.sp), maxLines = 1, overflow = TextOverflow.Ellipsis) - if (under != null) Text(under, style = warText(12.sp, War.brownSoft), maxLines = 1, overflow = TextOverflow.Ellipsis) - } - actions() - } - Box(Modifier.padding(vertical = 8.dp).fillMaxWidth().height(2.dp).background(Color(0xA0966E3C), RoundedCornerShape(1.dp))) - } -} - -/** The spellbook's side tab with an item icon in it (a page folded to its tab), lit gold when its page is open. */ -@Composable -fun SideTab(icon: String, label: String, on: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier) { - val war = LocalWar.current - Box(modifier.width(52.dp).height(60.dp).semantics { contentDescription = label }.warPress(sound = if (on) "close" else "open", onClick = onClick)) { - Canvas(Modifier.matchParentSize()) { - drawRoundRect(Color(WarPalette.SHADOW), Offset(0f, 2.dp.toPx()), size, CornerRadius(8.dp.toPx())) - val t = war?.piece("spellbook-skilllinetab") - if (t != null) drawWar(t, 0f, 0f, size.width, size.height) else drawRoundRect(War.woodDark, cornerRadius = CornerRadius(8.dp.toPx())) - val img = war?.icon(icon) - val x = 9.dp.toPx(); val y = 12.dp.toPx(); val s = 32.dp.toPx() - if (img != null) clipPath(roundPath(x, y, x + s, y + s, 6.dp.toPx())) { drawWar(img, x, y, s, s) } - else drawGlyphFor(icon, x + s / 2, y + s / 2, s * 0.8f) - if (on) drawRoundRect(War.gold, Offset(5.dp.toPx(), 8.dp.toPx()), Size(40.dp.toPx(), 40.dp.toPx()), CornerRadius(8.dp.toPx()), style = Stroke(2.5.dp.toPx())) - } - } -} - /** A dark rounded strip over the scene (the tooltip, the placing bar, the loading line): warm glass with a soft gold edge. */ @Composable fun GlassStrip(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) { @@ -677,35 +428,6 @@ fun GlassPanel(modifier: Modifier = Modifier, corbel: Boolean = true, content: @ } } -/** - * The catalogue bar's ground: the housing panel's stone warmed and darkened, rounded at the top, the wooden header along its - * top edge and the housing editor's corbels with leaves at its two top corners. - */ -@Composable -fun WoodBar(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) { - val war = LocalWar.current - val shape = RoundedCornerShape(topStart = WarSize.R_PANEL.dp, topEnd = WarSize.R_PANEL.dp) - Box(modifier) { - Box(Modifier.matchParentSize().shadow(10.dp, shape).clip(shape).drawBehind { - val stone = war?.piece("housing-basic-panel--stone-background") - if (stone != null) drawWar(stone, 0f, 0f, size.width, size.height) - drawRect(if (stone != null) Color(0xAA22170E) else War.woodDark) - }) - Canvas(Modifier.matchParentSize()) { - val head = war?.piece("housing-basic-container-woodheader") - val hh = 18.dp.toPx() - if (head != null) { - // only the header's own strip, over the bar's top edge - drawImage(head, IntOffset.Zero, IntSize(head.width, head.height), IntOffset(0, (-6).dp.toPx().roundToInt()), IntSize(size.width.roundToInt(), hh.roundToInt()), filterQuality = FilterQuality.Medium) - } else drawRect(War.wood, Offset(0f, -4.dp.toPx()), Size(size.width, 8.dp.toPx())) - val b = 58.dp.toPx() - war?.piece("decor-abilitybar-bookend-left")?.let { drawWar(it, 2.dp.toPx(), -b + 14.dp.toPx(), b, b) } - war?.piece("decor-abilitybar-bookend-right")?.let { drawWar(it, size.width - b - 2.dp.toPx(), -b + 14.dp.toPx(), b, b) } - } - Column(Modifier.fillMaxWidth().padding(horizontal = WarSize.GUTTER.dp, vertical = WarSize.GUTTER.dp), content = content) - } -} - /** The scene's name on the parchment ribbon (the game's neutral frame ribbon), in Morpheus. */ @Composable fun NameRibbon(text: String, modifier: Modifier = Modifier) { @@ -720,6 +442,7 @@ fun NameRibbon(text: String, modifier: Modifier = Modifier) { ) { Text(text, style = warTitle(19.sp), maxLines = 1, overflow = TextOverflow.Ellipsis) } } + /** * The slim top bar over the scene: a soft dark fade from the top, Back on the left, the name on its ribbon, then [actions] * (round buttons) on the right. The name gives way first on a narrow screen. @@ -759,50 +482,3 @@ fun Modifier.warScrollbar(state: LazyListState): Modifier = drawWithContent { drawRoundRect(Color(0x40785A32), Offset(x, 0f), Size(w, size.height), CornerRadius(w / 2)) drawRoundRect(War.amber, Offset(x, ((size.height - h) * (top / (1f - len).coerceAtLeast(0.0001f))).coerceIn(0f, size.height - h)), Size(w, h), CornerRadius(w / 2)) } - -/** A row of a list on parchment: a warm cream card (deeper and gold-edged when [selected]), an icon at its start. */ -@Composable -fun WarRow(onClick: () -> Unit, modifier: Modifier = Modifier, selected: Boolean = false, icon: String? = null, onLongPress: (() -> Unit)? = null, content: @Composable RowScope.() -> Unit) { - val war = LocalWar.current - val shape = RoundedCornerShape(WarSize.R_CARD.dp) - Row( - modifier.fillMaxWidth().heightIn(min = 56.dp).shadow(2.dp, shape).clip(shape) - .background(if (selected) War.parchmentDeep else Color(0xF0F6EBCF)).border(if (selected) 2.dp else 1.dp, if (selected) War.gold else War.edge, shape) - .warPress(onLongPress = onLongPress, onClick = onClick).padding(horizontal = 12.dp, vertical = 6.dp), - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - if (icon != null) Canvas(Modifier.size(40.dp)) { - val img = war?.icon(icon) - if (img != null) clipPath(roundPath(0f, 0f, size.width, size.height, 10.dp.toPx())) { drawWar(img, 0f, 0f, size.width, size.height) } - else { drawRoundRect(War.woodDark, cornerRadius = CornerRadius(10.dp.toPx())); drawGlyphFor(icon, center.x, center.y, size.minDimension * 0.6f) } - } - content() - } -} - -/** - * A screen of the editor's menus in the build-mode look (the projects, the cast, the scenes): the top bar's Back and - * name ribbon with [actions], the content on a spellbook page over the warm dark ground, never taller than the screen. - */ -@Composable -fun WarScreen(title: String, onBack: () -> Unit, actions: @Composable RowScope.() -> Unit = {}, content: @Composable BoxScope.() -> Unit) { - Box(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color(0xFF2A1C12), Color(0xFF140D08))))) { - Column(Modifier.fillMaxSize()) { - TopBar(title, onBack, actions = actions) - BookPage(Modifier.weight(1f).fillMaxWidth().padding(start = 12.dp, end = 12.dp, bottom = 12.dp), content = content) - } - } -} - -/** A dialog on a parchment page in the middle of the screen (a name to type, a question): never wider than the screen. */ -@Composable -fun WarDialog(onDismiss: () -> Unit, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) { - Overlay(onDismiss) { - BookPage(modifier.widthIn(max = 520.dp).padding(16.dp), ribbon = false) { - Column(verticalArrangement = Arrangement.spacedBy(12.dp), content = content) - } - } -} - -/** The plain round shape, for callers that clip to it. */ -val WarCircle = CircleShape diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WowMenus.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WowMenus.kt index 66da5259..690b220c 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WowMenus.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WowMenus.kt @@ -241,31 +241,6 @@ fun RedButton(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, } } -/** - * Buttons stacked as the Game Menu has them: one column, or [cols] side by side when the screen is short (the cover screen on - * its side), each [width] wide. - */ -@Composable -fun RedStack(buttons: List>, label: (T) -> String, cols: Int, width: Dp, onPick: (T) -> Unit, modifier: Modifier = Modifier) { - val rows = ChromeLayout.rows(buttons.size, cols) - Row(modifier, horizontalArrangement = Arrangement.spacedBy(10.dp)) { - for (c in 0 until cols) Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - for (b in buttons.drop(c * rows).take(rows)) RedButton(label(b.item), { onPick(b.item) }, Modifier.width(width), enabled = b.enabled) - } - } -} - -/** The Game Menu: the metal frame, its title, the red buttons stacked ([Menus.game]), over the dimmed screen. */ -@Composable -fun GameMenuPanel(buttons: List>, cols: Int, onPick: (GameMenuItem) -> Unit, onDismiss: () -> Unit, title: String = "Game Menu", subtitle: String? = null) { - Overlay(onDismiss) { - WowWindow(title, onClose = null, modifier = Modifier.width((cols * 240 + (cols - 1) * 10 + 48).dp)) { - if (subtitle != null) Text(subtitle, style = frizStyle(12.sp, WowColors.grey), maxLines = 1, modifier = Modifier.align(Alignment.CenterHorizontally).padding(bottom = 6.dp)) - RedStack(buttons, { it.label }, cols, 240.dp, onPick, Modifier.align(Alignment.CenterHorizontally).padding(top = 4.dp, bottom = 4.dp)) - } - } -} - // ------------------------------------------------------------------------------------------------ dropdowns and tooltips /** The game's tooltip box: near black, a thin grey edge, its corner pieces. */ @@ -322,41 +297,6 @@ fun WowCheckBox(checked: Boolean, enabled: Boolean = true, size: Dp = 26.dp) { } } -/** - * A WoW dropdown list on the tooltip's dark box: an optional gold [title], then plain rows of white words with small icons - * (or check boxes), dimmed when they can't be used, Delete in red, thin rules between the groups. Never taller than - * [maxHeight]: its rows scroll. - */ -@Composable -fun WowDropdownList(title: String?, rows: List, onPick: (MenuRow) -> Unit, modifier: Modifier = Modifier, maxHeight: Dp = 600.dp) { - WowTooltipBox(modifier) { - Column(Modifier.padding(vertical = 4.dp)) { - if (title != null) Text(title, style = frizStyle(15.sp), maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.padding(horizontal = 14.dp).height(EditorMenus.TITLE.dp).padding(top = 8.dp)) - val list = rememberLazyListState() - LazyColumn(Modifier.heightIn(max = maxHeight).warScrollbar(list), list) { - itemsIndexed(rows, key = { _, r -> r.action.name }, contentType = { _, r -> if (r.checked != null) 1 else 0 }) { _, r -> - Column { - if (r.ruleBefore) Box(Modifier.padding(horizontal = 12.dp, vertical = 6.dp).fillMaxWidth().height(1.dp).background(Color(0xFF5A5A5F))) - MenuRowView(r) { onPick(r) } - } - } - } - } - } -} - -@Composable -private fun MenuRowView(r: MenuRow, onClick: () -> Unit) { - Row( - Modifier.fillMaxWidth().height(EditorMenus.ROW.dp).warPress(r.enabled, onClick = onClick).padding(horizontal = 14.dp), - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), - ) { - if (r.checked != null) WowCheckBox(r.checked, r.enabled, 24.dp) else MenuIcon(r.icon, r.enabled) - Text(r.label, style = frizStyle(15.sp, when { !r.enabled -> Dim; r.danger -> Red; else -> Ink }), maxLines = 1, overflow = TextOverflow.Ellipsis) - } -} - /** A WoW-style text button: gold words (red for [danger]), 48 dp to touch, no frame (a context row's Rename, Delete...). */ @Composable fun TextAction(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, danger: Boolean = false) { @@ -526,101 +466,6 @@ fun WowTextField(value: String, onChange: (String) -> Unit, hint: String, modifi } } -// ------------------------------------------------------------------------------------------------ the action bar - -/** What a slot shows: the housing editor's tool picture ([decor]), an item icon, a gold glyph, or the three dots of More. */ -data class SlotFace(val decor: String? = null, val icon: String? = null, val glyph: String? = null, val dots: Boolean = false) - -/** The face of each slot. */ -fun slotFace(s: ActionSlot): SlotFace = when (s) { - ActionSlot.SELECT -> SlotFace(decor = "decor-ability-move-default") - ActionSlot.ROTATE -> SlotFace(decor = "decor-ability-expert-rotate-default") - ActionSlot.SCALE -> SlotFace(decor = "decor-ability-expert-scale-default") - ActionSlot.DELETE -> SlotFace(glyph = WarIcons.DELETE) - ActionSlot.ADD -> SlotFace(icon = "tab.props") - ActionSlot.MORE -> SlotFace(dots = true) -} - -/** - * An action bar slot (the game's): the icon in the action bar's frame, a gold edge while [lit], dimmed when it can't be used, - * its name under it. [size] square; a long press says what it does. - */ -@Composable -fun ActionSlotButton(face: SlotFace, label: String, onClick: () -> Unit, size: Dp, modifier: Modifier = Modifier, lit: Boolean = false, enabled: Boolean = true, onLongPress: (() -> Unit)? = null) { - val war = LocalWar.current - Column(modifier.width(size), horizontalAlignment = Alignment.CenterHorizontally) { - Box(Modifier.size(size).semantics { contentDescription = label }.warPress(enabled, onLongPress = onLongPress, onClick = onClick)) { - Canvas(Modifier.matchParentSize()) { - val s = this.size.width; val ins = s * 0.1f; val inner = s - 2 * ins - val a = if (enabled) 1f else 0.42f - drawRoundRect(Color(WarPalette.SHADOW), Offset(0f, 2.dp.toPx()), this.size, CornerRadius(4.dp.toPx())) - drawRoundRect(Color(0xFF18120C), Offset(ins, ins), Size(inner, inner), CornerRadius(4.dp.toPx())) - var drawn = false - face.decor?.let { n -> - war?.piece(n)?.let { p -> - val k = (p.width * 0.17f).toInt() - clipPath(roundPath(ins, ins, ins + inner, ins + inner, 4.dp.toPx())) { - drawImage(p, IntOffset(k, k), IntSize(p.width - 2 * k, p.height - 2 * k), IntOffset(ins.roundToInt(), ins.roundToInt()), - IntSize(inner.roundToInt(), inner.roundToInt()), alpha = a, filterQuality = FilterQuality.Medium) - } - drawn = true - } - } - if (!drawn) face.icon?.let { k -> war?.icon(k)?.let { - clipPath(roundPath(ins, ins, ins + inner, ins + inner, 4.dp.toPx())) { drawWar(it, ins, ins, inner, inner, a) } - drawn = true - } } - if (!drawn) face.glyph?.let { g -> war?.piece(g)?.let { drawFitted(it, center.x, center.y, s * 0.5f, a); drawn = true } } - if (!drawn && face.dots) { - for (i in -1..1) drawCircle(War.gold, s * 0.06f, Offset(center.x + i * s * 0.18f, center.y), alpha = a) - drawn = true - } - if (!drawn) drawGlyphFor(face.glyph ?: face.icon ?: face.decor, center.x, center.y, s * 0.5f, War.gold, a) - val frame = war?.piece("ui-hud-actionbar-iconframe") - if (frame != null) drawWar(frame, 0f, 0f, s, s) else drawRoundRect(Edge, cornerRadius = CornerRadius(4.dp.toPx()), style = Stroke(2.dp.toPx())) - if (!enabled) drawRoundRect(Color(0x9614100A), Offset(ins, ins), Size(inner, inner), CornerRadius(4.dp.toPx())) - if (lit) drawRoundRect(War.gold, Offset(ins * 0.6f, ins * 0.6f), Size(s - 1.2f * ins, s - 1.2f * ins), CornerRadius(5.dp.toPx()), style = Stroke(2.5.dp.toPx())) - } - } - Text(label, style = frizStyle(11.sp, if (enabled) Ink else Dim), maxLines = 1, modifier = Modifier.padding(top = 2.dp)) - } -} - -/** - * The action bar along the bottom: six framed slots ([ActionSlot]) on the housing editor's ability bar, its wooden corbels at - * the ends. [slot] from ChromeLayout. - */ -@Composable -fun ActionBarView(slot: Dp, content: @Composable RowScope.() -> Unit, modifier: Modifier = Modifier) { - val war = LocalWar.current - val shape = RoundedCornerShape(14.dp) - Box(modifier) { - Box(Modifier.matchParentSize().shadow(6.dp, shape).clip(shape).background(Color(0xD718110B)).border(1.5.dp, Color(0xFF8A6A3A), shape)) - Canvas(Modifier.matchParentSize()) { - val b = 46.dp.toPx() - war?.piece("decor-abilitybar-bookend-left")?.let { drawWar(it, -b * 0.55f, -b * 0.45f, b, b) } - war?.piece("decor-abilitybar-bookend-right")?.let { drawWar(it, size.width - b * 0.45f, -b * 0.45f, b, b) } - } - Row(Modifier.padding(horizontal = 18.dp).padding(top = 6.dp, bottom = 4.dp), horizontalArrangement = Arrangement.spacedBy(ChromeLayout.GAP.dp), content = content) - } -} - -/** The Menu button (top left): the action bar's frame with a gold cog, as the game's micro menu sits in a corner. */ -@Composable -fun MenuCogButton(onClick: () -> Unit, modifier: Modifier = Modifier) { - val war = LocalWar.current - Box(modifier.size(52.dp).semantics { contentDescription = "Menu" }.warPress(sound = "open", onClick = onClick)) { - Canvas(Modifier.matchParentSize()) { - val s = size.width; val ins = s * 0.1f - drawRoundRect(Color(WarPalette.SHADOW), Offset(0f, 2.dp.toPx()), size, CornerRadius(4.dp.toPx())) - drawRoundRect(Color(0xFF281C12), Offset(ins, ins), Size(s - 2 * ins, s - 2 * ins), CornerRadius(4.dp.toPx())) - drawGlyph(WarGlyph.COG, center.x, center.y, s * 0.52f, War.gold) - val frame = war?.piece("ui-hud-actionbar-iconframe") - if (frame != null) drawWar(frame, 0f, 0f, s, s) else drawRoundRect(Edge, cornerRadius = CornerRadius(4.dp.toPx()), style = Stroke(2.dp.toPx())) - } - } -} - // ------------------------------------------------------------------------------------------------ lists /** @@ -670,7 +515,3 @@ fun WowListRow( @Composable fun WowNote(text: String, modifier: Modifier = Modifier, color: Color = Dim) = Text(text, style = frizStyle(13.sp, color), modifier = modifier) - -/** Space that pushes what follows to the end of a row or column. */ -@Composable -fun RowScope.Fill() = Spacer(Modifier.weight(1f)) diff --git a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WowWidgets.kt b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WowWidgets.kt index ebeb4842..f64aa0ac 100644 --- a/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WowWidgets.kt +++ b/wifecraft/android/app/src/main/java/com/logie/wifecraft/ui/WowWidgets.kt @@ -44,6 +44,42 @@ import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlin.math.roundToInt +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.Image +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.detectHorizontalDragGestures +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.collectIsHoveredAsState +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.shadow +import androidx.compose.ui.geometry.CornerRadius +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.style.TextOverflow /** WoW's colours: the gold of names and buttons, white words, the parchment's ink. */ object WowColors { @@ -297,3 +333,452 @@ fun GossipOption(text: String, onClick: () -> Unit, modifier: Modifier = Modifie fun Black(alpha: Float) { if (alpha > 0.001f) Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = alpha.coerceIn(0f, 1f)))) } + +// ================================================================================================ the front menus' kit +// +// The title, the scene's setup, Options and Updates in the current game's look (Dragonflight and The War Within's menus): +// dark slate panels with a thin gold trim, rounded buttons that glow when hovered or pressed, gold Friz headings over pale +// words, one set of spacing and type sizes ([WifeTheme]). They draw with the game's fonts (LocalArt) and play the game's +// interface sounds (LocalSounds: open, close, click, tab, check_on/off); every touch target is 48 dp or more and every motion +// is MenuMotion's / FrontMotion's (none under reduced motion). The creator keeps its own look (WarWidgets, RedButton). + +/** The front menus' colours, spacing, corners and type, in one place. */ +object WifeTheme { + // colours + val slate = Color(0xF2171C24) + val slateDeep = Color(0xF20B0E13) + val slateRaised = Color(0xFF232A35) + val trim = Color(0xFFC9A55C) + val trimSoft = Color(0x59C9A55C) + val glow = Color(0xFFFFD37A) + val gold = WowColors.gold + val text = Color(0xFFF1E9DA) + val textDim = Color(0xFFA8A49C) + val danger = Color(0xFFE5574A) + val good = Color(0xFF86D98A) + val primaryTop = Color(0xFF9A2416) + val primaryBottom = Color(0xFF5C0F08) + val secondaryTop = Color(0xFF2C3440) + val secondaryBottom = Color(0xFF181D25) + val track = Color(0xFF0A0D12) + + // spacing, sizes, corners + val gapXs = 4.dp + val gapS = 8.dp + val gapM = 12.dp + val gapL = 16.dp + val gapXl = 24.dp + val touch = 48.dp + val radius = 14.dp + val buttonRadius = 10.dp + val trimWidth = 1.dp + + // type sizes + val display = 50.sp + val title = 20.sp + val heading = 16.sp + val label = 15.sp + val body = 14.sp + val caption = 12.sp + + @Composable fun displayStyle(size: TextUnit = display): TextStyle = morpheusStyle(size) + @Composable fun titleStyle(): TextStyle = frizStyle(title, gold) + @Composable fun headingStyle(): TextStyle = frizStyle(heading, gold) + @Composable fun labelStyle(color: Color = text): TextStyle = frizStyle(label, color) + @Composable fun bodyStyle(color: Color = text): TextStyle = frizStyle(body, color) + @Composable fun captionStyle(color: Color = textDim): TextStyle = frizStyle(caption, color, shadow = false) +} + +/** How a [WifeButton] looks: the game's red (the main action), slate (the others), or words alone. */ +enum class WifeButtonKind { PRIMARY, SECONDARY, QUIET } + +/** The slate body with its gold trim and a faint light along its top edge, in [shape]'s corners. */ +fun Modifier.wifeSurface(radius: Dp = WifeTheme.radius, raised: Boolean = false): Modifier = this + .shadow(if (raised) 14.dp else 8.dp, RoundedCornerShape(radius), clip = false) + .clip(RoundedCornerShape(radius)) + .drawBehind { + val r = CornerRadius(radius.toPx()) + drawRoundRect(Brush.verticalGradient(listOf(WifeTheme.slate, WifeTheme.slateDeep)), cornerRadius = r) + // the light from above: a thin pale band under the top edge + drawRect(Brush.verticalGradient(listOf(Color(0x14FFFFFF), Color.Transparent), endY = 36.dp.toPx())) + val w = WifeTheme.trimWidth.toPx() + drawRoundRect(WifeTheme.trim.copy(alpha = 0.85f), Offset(w / 2, w / 2), Size(size.width - w, size.height - w), r, style = Stroke(w)) + // the inner hairline, as the game's frames have + val i = 4.dp.toPx() + drawRoundRect(WifeTheme.trimSoft, Offset(i, i), Size(size.width - 2 * i, size.height - 2 * i), CornerRadius((radius.toPx() - i).coerceAtLeast(0f)), style = Stroke(w)) + } + +/** A slate panel holding [content] in a column with the theme's padding. */ +@Composable +fun WifePanel(modifier: Modifier = Modifier, padding: Dp = WifeTheme.gapL, content: @Composable ColumnScope.() -> Unit) { + Column(modifier.wifeSurface().padding(padding), content = content) +} + +/** A gold rule with a small diamond in its middle (under a window's title). */ +@Composable +fun WifeDivider(modifier: Modifier = Modifier) { + Canvas(modifier.fillMaxWidth().height(9.dp)) { + val y = size.height / 2; val cx = size.width / 2; val d = 4.dp.toPx() + drawLine(Brush.horizontalGradient(listOf(Color.Transparent, WifeTheme.trim, Color.Transparent)), Offset(0f, y), Offset(size.width, y), 1.dp.toPx()) + val p = androidx.compose.ui.graphics.Path().apply { moveTo(cx, y - d); lineTo(cx + d, y); lineTo(cx, y + d); lineTo(cx - d, y); close() } + drawPath(p, WifeTheme.trim) + } +} + +/** A small gold heading over a group of rows, with a hairline after it. */ +@Composable +fun WifeSectionHeader(text: String, modifier: Modifier = Modifier) { + Row(modifier.fillMaxWidth().padding(top = WifeTheme.gapS, bottom = WifeTheme.gapXs), verticalAlignment = Alignment.CenterVertically) { + Text(text.uppercase(), style = frizStyle(WifeTheme.caption, WifeTheme.gold).copy(letterSpacing = 1.2.sp), maxLines = 1) + Box(Modifier.padding(start = WifeTheme.gapS).weight(1f).height(1.dp).background(WifeTheme.trimSoft)) + } +} + +/** + * A rounded button, 48 dp high at least: [kind] the game's red, slate, or words alone; a soft gold glow while hovered (a mouse + * or a stylus) or pressed, the press's sink (MenuMotion), the interface's [sound], a second tap in the quiet time ignored. + */ +@Composable +fun WifeButton( + text: String, + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + kind: WifeButtonKind = WifeButtonKind.SECONDARY, + sound: String = "click", +) { + val play = LocalSounds.current + val source = remember { MutableInteractionSource() } + val pressed by source.collectIsPressedAsState() + val hovered by source.collectIsHoveredAsState() + val reduced = reduceMotion() + val glow by animateFloatAsState( + when { !enabled -> 0f; pressed -> 1f; hovered -> 0.6f; else -> 0f }, + tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced)), label = "glow", + ) + val sink by animateFloatAsState(MenuMotion.pressScale(pressed && enabled, reduced), tween(MenuMotion.duration(MenuMotion.PRESS_MS, reduced)), label = "press") + val gate = rememberClickGate() + val shape = RoundedCornerShape(WifeTheme.buttonRadius) + Box( + modifier + .heightIn(min = WifeTheme.touch) + .graphicsLayer { scaleX = sink; scaleY = sink } + .hoverable(source, enabled) + .clickable(source, null, enabled = enabled, role = Role.Button, onClick = { if (gate.pass()) { play(sound); onClick() } }) + .drawBehind { + val r = CornerRadius(WifeTheme.buttonRadius.toPx()) + val a = if (enabled) 1f else 0.45f + when (kind) { + WifeButtonKind.PRIMARY -> drawRoundRect(Brush.verticalGradient(listOf(WifeTheme.primaryTop, WifeTheme.primaryBottom)), cornerRadius = r, alpha = a) + WifeButtonKind.SECONDARY -> drawRoundRect(Brush.verticalGradient(listOf(WifeTheme.secondaryTop, WifeTheme.secondaryBottom)), cornerRadius = r, alpha = a) + WifeButtonKind.QUIET -> if (glow > 0f) drawRoundRect(Color(0x14FFFFFF), cornerRadius = r) + } + if (glow > 0f) drawRoundRect( + Brush.radialGradient(listOf(WifeTheme.glow.copy(alpha = 0.32f * glow), Color.Transparent), center = Offset(size.width / 2, size.height), radius = (size.width * 0.6f).coerceAtLeast(1f)), + cornerRadius = r, + ) + if (kind != WifeButtonKind.QUIET) { + // the top's sheen and the gold edge (brighter as it glows) + drawRoundRect(Brush.verticalGradient(listOf(Color(0x22FFFFFF), Color.Transparent), endY = size.height * 0.5f), cornerRadius = r) + val w = (1f + glow).dp.toPx() + val edge = if (enabled) WifeTheme.trim.copy(alpha = 0.7f + 0.3f * glow) else WifeTheme.trimSoft + drawRoundRect(edge, Offset(w / 2, w / 2), Size(size.width - w, size.height - w), r, style = Stroke(w)) + } + } + .clip(shape) + .padding(horizontal = WifeTheme.gapL, vertical = WifeTheme.gapS), + contentAlignment = Alignment.Center, + ) { + val color = when { + !enabled -> WowColors.grey + kind == WifeButtonKind.QUIET -> WifeTheme.gold + else -> if (glow > 0.5f) Color.White else WifeTheme.gold + } + Text(text, style = frizStyle(WifeTheme.label, color), textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis) + } +} + +/** + * A window in the front menus' look: a slate panel, its [title] in gold with the rule under it, a round close button ([onClose] + * null: none), optional [tabs] under the title, the [content] (the caller scrolls it), and a [footer] row of buttons at its foot. + * It plays the interface's open sound as it first shows; it fades and grows in unless an [Overlay] moves it already. + */ +@Composable +fun WifeWindow( + title: String, + onClose: (() -> Unit)?, + modifier: Modifier = Modifier, + subtitle: String? = null, + tabs: List = emptyList(), + tab: Int = 0, + onTab: (Int) -> Unit = {}, + footer: (@Composable RowScope.() -> Unit)? = null, + content: @Composable ColumnScope.() -> Unit, +) { + val play = LocalSounds.current + LaunchedEffect(Unit) { play("open") } + val enter = if (LocalInMovingOverlay.current) null else rememberEnter() + Column( + (if (enter != null) modifier.windowMotion { enter.value } else modifier) + .wifeSurface(raised = true) + .padding(start = WifeTheme.gapL, end = WifeTheme.gapS, top = WifeTheme.gapXs, bottom = WifeTheme.gapL), + ) { + Row(Modifier.fillMaxWidth().heightIn(min = WifeTheme.touch), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f).padding(end = WifeTheme.gapS)) { + Text(title, style = WifeTheme.titleStyle(), maxLines = 1, overflow = TextOverflow.Ellipsis) + if (subtitle != null) Text(subtitle, style = WifeTheme.captionStyle(), maxLines = 2, overflow = TextOverflow.Ellipsis) + } + if (onClose != null) WifeCloseButton(onClose) + } + Column(Modifier.padding(end = WifeTheme.gapS)) { + WifeDivider(Modifier.padding(bottom = WifeTheme.gapS)) + if (tabs.isNotEmpty()) WifeTabs(tabs, tab, onTab, Modifier.padding(bottom = WifeTheme.gapM)) + } + Column(Modifier.weight(1f, fill = false).padding(end = WifeTheme.gapS), content = content) + if (footer != null) Row( + Modifier.fillMaxWidth().padding(top = WifeTheme.gapM, end = WifeTheme.gapS), + horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapS, Alignment.End), verticalAlignment = Alignment.CenterVertically, content = footer, + ) + } +} + +/** The round close button: a thin gold ring with an X, 48 dp to touch; plays the close sound. */ +@Composable +fun WifeCloseButton(onClick: () -> Unit, modifier: Modifier = Modifier) { + val source = remember { MutableInteractionSource() } + val hovered by source.collectIsHoveredAsState() + Box( + modifier.size(WifeTheme.touch).semantics { contentDescription = "Close" }.hoverable(source).warPress(sound = "close", onClick = onClick), + contentAlignment = Alignment.Center, + ) { + Canvas(Modifier.size(30.dp)) { + val c = center; val r = size.minDimension / 2 + drawCircle(if (hovered) Color(0x33FFD37A) else Color(0x1AFFFFFF), r) + drawCircle(WifeTheme.trim, r - 0.5.dp.toPx(), style = Stroke(1.dp.toPx())) + val k = r * 0.38f; val w = 1.8.dp.toPx() + drawLine(WifeTheme.gold, Offset(c.x - k, c.y - k), Offset(c.x + k, c.y + k), w) + drawLine(WifeTheme.gold, Offset(c.x + k, c.y - k), Offset(c.x - k, c.y + k), w) + } + } +} + +/** + * Tabs as the current game's: words side by side, the chosen one white with a gold bar under it that slides between them. + * Equal parts when they fit, else a strip that scrolls ([FrontLayout.tabsScroll]). Each is 48 dp high. + */ +@Composable +fun WifeTabs(labels: List, selected: Int, onSelect: (Int) -> Unit, modifier: Modifier = Modifier) { + val reduced = reduceMotion() + val at by animateFloatAsState(selected.toFloat(), tween(MenuMotion.duration(FrontMotion.TAB_MS, reduced)), label = "tab") + BoxWithConstraints(modifier.fillMaxWidth()) { + val scroll = FrontLayout.tabsScroll(maxWidth.value, labels.size) + val row = if (scroll) Modifier.horizontalScroll(rememberScrollState()) else Modifier.fillMaxWidth() + Box(Modifier.drawBehind { drawRect(WifeTheme.trimSoft, Offset(0f, size.height - 1.dp.toPx()), Size(size.width, 1.dp.toPx())) }) { + Row(row) { + labels.forEachIndexed { i, label -> + val on = i == selected + Box( + (if (scroll) Modifier.widthIn(min = 96.dp) else Modifier.weight(1f)).height(WifeTheme.touch) + .semantics { this.selected = on } + .warPress(sound = "tab") { if (!on) onSelect(i) } + .drawBehind { + // the bar under the chosen tab (sliding across while the choice changes) + val d = 1f - kotlin.math.abs(at - i).coerceAtMost(1f) + if (d > 0f) { + val w = size.width * 0.7f * d + drawRoundRect(WifeTheme.gold, Offset((size.width - w) / 2, size.height - 3.dp.toPx()), Size(w, 3.dp.toPx()), CornerRadius(1.5.dp.toPx())) + } + } + .padding(horizontal = WifeTheme.gapS), + contentAlignment = Alignment.Center, + ) { + Text(label, style = frizStyle(WifeTheme.label, if (on) Color.White else WifeTheme.gold), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } + } + } +} + +/** A slider: a dark track, its gold fill, a round thumb that glows while held; taps and drags set [value] (0..1). 48 dp high. */ +@Composable +fun WifeSlider(value: Float, onChange: (Float) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, onFinished: () -> Unit = {}) { + val change by rememberUpdatedState(onChange) + val finished by rememberUpdatedState(onFinished) + var held by remember { mutableStateOf(false) } + val reduced = reduceMotion() + val glow by animateFloatAsState(if (held) 1f else 0f, tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced)), label = "thumb") + val v = value.coerceIn(0f, 1f) + Canvas( + modifier.height(WifeTheme.touch) + .then(if (!enabled) Modifier else Modifier + .pointerInput(Unit) { + val k = 22.dp.toPx() + detectTapGestures(onPress = { held = true; tryAwaitRelease(); held = false }) { o -> + change(((o.x - k / 2) / (size.width - k)).coerceIn(0f, 1f)); finished() + } + } + .pointerInput(Unit) { + val k = 22.dp.toPx() + detectHorizontalDragGestures( + onDragStart = { held = true }, + onDragEnd = { held = false; finished() }, + onDragCancel = { held = false }, + ) { ch, _ -> ch.consume(); change(((ch.position.x - k / 2) / (size.width - k)).coerceIn(0f, 1f)) } + }), + ) { + val k = 22.dp.toPx(); val th = 6.dp.toPx(); val y = size.height / 2; val x0 = k / 2; val w = size.width - k + val a = if (enabled) 1f else 0.45f + drawRoundRect(WifeTheme.track, Offset(x0, y - th / 2), Size(w, th), CornerRadius(th / 2), alpha = a) + drawRoundRect(WifeTheme.trimSoft, Offset(x0, y - th / 2), Size(w, th), CornerRadius(th / 2), style = Stroke(1.dp.toPx()), alpha = a) + drawRoundRect(Brush.horizontalGradient(listOf(Color(0xFF8A6A2A), WifeTheme.gold)), Offset(x0, y - th / 2), Size(w * v, th), CornerRadius(th / 2), alpha = a) + val kx = x0 + w * v + if (glow > 0f) drawCircle(WifeTheme.glow.copy(alpha = 0.3f * glow), k * 0.95f, Offset(kx, y)) + drawCircle(Brush.verticalGradient(listOf(Color(0xFFF6E2B0), Color(0xFFB08A3A)), startY = y - k / 2, endY = y + k / 2), k / 2, Offset(kx, y), alpha = a) + drawCircle(Color(0xFF3A2A10), k / 2, Offset(kx, y), style = Stroke(1.dp.toPx()), alpha = a) + } +} + +/** + * A slider row (the Sound page's): the label, the slider, the value. Side by side, or the label over the slider on a narrow + * row ([FrontLayout.sliderStacked]); the row's height never changes as the value does. + */ +@Composable +fun WifeSliderRow( + label: String, + value: Int, + onChange: (Int) -> Unit, + modifier: Modifier = Modifier, + valueText: String = if (value <= 0) "Off" else "$value%", + range: IntRange = 0..100, + enabled: Boolean = true, +) { + val span = (range.last - range.first).coerceAtLeast(1) + val frac = (value - range.first).toFloat() / span + val set: (Float) -> Unit = { f -> onChange(range.first + (f * span).roundToInt()) } + BoxWithConstraints(modifier.fillMaxWidth().semantics { stateDescription = valueText }) { + val labelStyle = WifeTheme.labelStyle(if (enabled) WifeTheme.text else WifeTheme.textDim) + if (FrontLayout.sliderStacked(maxWidth.value)) { + Column { + Row(verticalAlignment = Alignment.CenterVertically) { + Text(label, style = labelStyle, maxLines = 2, modifier = Modifier.weight(1f)) + Text(valueText, style = WifeTheme.bodyStyle(WifeTheme.gold), maxLines = 1) + } + WifeSlider(frac, set, Modifier.fillMaxWidth(), enabled) + } + } else { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapM)) { + Text(label, style = labelStyle, maxLines = 2, modifier = Modifier.weight(0.4f)) + WifeSlider(frac, set, Modifier.weight(0.6f), enabled) + Text(valueText, style = WifeTheme.bodyStyle(WifeTheme.gold), maxLines = 1, textAlign = TextAlign.End, modifier = Modifier.width(52.dp)) + } + } + } +} + +/** A switch row: the label (and a line under it), a rounded switch at its end; the whole row toggles, 48 dp or more. */ +@Composable +fun WifeSwitchRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit, modifier: Modifier = Modifier, detail: String? = null, enabled: Boolean = true) { + val reduced = reduceMotion() + val t by animateFloatAsState(if (checked) 1f else 0f, tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced)), label = "switch") + val knob by animateColorAsState(if (checked) WifeTheme.gold else Color(0xFF9A958C), tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced)), label = "knob") + Row( + modifier.fillMaxWidth().heightIn(min = WifeTheme.touch) + .semantics { stateDescription = if (checked) "On" else "Off" } + .warPress(enabled, sound = if (checked) "check_off" else "check_on") { onChange(!checked) }, + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(WifeTheme.gapM), + ) { + Column(Modifier.weight(1f)) { + Text(label, style = WifeTheme.labelStyle(if (enabled) WifeTheme.text else WifeTheme.textDim), maxLines = 2) + if (detail != null) Text(detail, style = WifeTheme.captionStyle(), maxLines = 3) + } + Canvas(Modifier.width(46.dp).height(26.dp)) { + val a = if (enabled) 1f else 0.45f + val r = CornerRadius(size.height / 2) + drawRoundRect(lerpColor(WifeTheme.track, Color(0xFF5A4318), t), cornerRadius = r, alpha = a) + drawRoundRect(WifeTheme.trim.copy(alpha = 0.5f + 0.5f * t), cornerRadius = r, style = Stroke(1.dp.toPx()), alpha = a) + val d = size.height - 6.dp.toPx() + val x = 3.dp.toPx() + d / 2 + (size.width - d - 6.dp.toPx()) * t + drawCircle(knob, d / 2, Offset(x, size.height / 2), alpha = a) + } + } +} + +private fun lerpColor(a: Color, b: Color, t: Float): Color = androidx.compose.ui.graphics.lerp(a, b, t.coerceIn(0f, 1f)) + +/** A slim progress bar: a dark track, a gold fill, a light running along it while [busy] and nothing can be counted. */ +@Composable +fun WifeProgress(fraction: Float, modifier: Modifier = Modifier) { + val f = fraction.coerceIn(0f, 1f) + Canvas(modifier.fillMaxWidth().height(10.dp)) { + val r = CornerRadius(size.height / 2) + drawRoundRect(WifeTheme.track, cornerRadius = r) + if (f > 0f) drawRoundRect(Brush.horizontalGradient(listOf(Color(0xFF8A6A2A), WifeTheme.gold)), size = Size(size.width * f, size.height), cornerRadius = r) + drawRoundRect(WifeTheme.trimSoft, cornerRadius = r, style = Stroke(1.dp.toPx())) + } +} + +/** + * A picture card (a scene, an NPC): the picture rounded in a slate frame (its initial until it is drawn), the gold trim and a + * glow when [selected], the name under it in two lines at most. [side] square; dimmed when not [enabled]. + */ +@Composable +fun WifeCard( + name: String, + picture: ImageBitmap?, + side: Dp, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, +) { + val reduced = reduceMotion() + val lit by animateFloatAsState(if (selected) 1f else 0f, tween(MenuMotion.duration(FrontMotion.GLOW_MS, reduced)), label = "card") + val shape = RoundedCornerShape(WifeTheme.buttonRadius) + Column(modifier.width(side).graphicsLayer { alpha = if (enabled || selected) 1f else 0.5f }, horizontalAlignment = Alignment.CenterHorizontally) { + Box( + Modifier.size(side) + .semantics { contentDescription = name; this.selected = selected } + .warPress(enabled || selected, sound = "select", onClick = onClick) + .drawBehind { + if (lit > 0f) drawRoundRect(WifeTheme.glow.copy(alpha = 0.28f * lit), Offset(-3.dp.toPx(), -3.dp.toPx()), + Size(size.width + 6.dp.toPx(), size.height + 6.dp.toPx()), CornerRadius((WifeTheme.buttonRadius + 3.dp).toPx())) + } + .clip(shape) + .background(Brush.verticalGradient(listOf(WifeTheme.slateRaised, WifeTheme.slateDeep))) + .border(if (selected) 2.dp else 1.dp, if (selected) WifeTheme.gold else WifeTheme.trimSoft, shape), + contentAlignment = Alignment.Center, + ) { + if (picture != null) Image(picture, null, Modifier.matchParentSize(), contentScale = ContentScale.Crop) + else Text(name.take(1).uppercase(), style = WifeTheme.displayStyle(28.sp).copy(color = WifeTheme.textDim)) + } + Text(name, style = frizStyle(WifeTheme.caption, if (selected) WifeTheme.gold else WifeTheme.text), maxLines = 2, overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, modifier = Modifier.padding(top = WifeTheme.gapXs)) + } +} + +/** A rounded chip (a cast member): the name, an x to take it out; 48 dp to touch. */ +@Composable +fun WifeChip(text: String, onClick: () -> Unit, modifier: Modifier = Modifier, trailing: String? = "×") { + val shape = RoundedCornerShape(50) + Box(modifier.heightIn(min = WifeTheme.touch).warPress(onClick = onClick), contentAlignment = Alignment.Center) { + Row( + Modifier.clip(shape).background(WifeTheme.slateRaised).border(1.dp, WifeTheme.trim.copy(alpha = 0.7f), shape) + .padding(horizontal = WifeTheme.gapM, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text(text, style = frizStyle(WifeTheme.body, WifeTheme.text), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 160.dp)) + if (trailing != null) Text(trailing, style = frizStyle(WifeTheme.body, WifeTheme.gold), maxLines = 1) + } + } +} + +/** A line of help on a front-menu panel: dim, wrapping, never clipped. */ +@Composable +fun WifeNote(text: String, modifier: Modifier = Modifier, color: Color = WifeTheme.textDim) { + Text(text, style = frizStyle(WifeTheme.caption, color, shadow = false), modifier = modifier) +} + +/** Space between groups of rows. */ +@Composable +fun WifeGap(space: Dp = WifeTheme.gapS) = Spacer(Modifier.height(space)) diff --git a/wifecraft/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/wifecraft/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000..73f2676b --- /dev/null +++ b/wifecraft/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png b/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png new file mode 100644 index 00000000..8111a971 Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_background.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..407197ac Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.png b/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.png new file mode 100644 index 00000000..0e3d1259 Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png b/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png new file mode 100644 index 00000000..a9a165d6 Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_background.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..c7e3cd03 Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.png b/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.png new file mode 100644 index 00000000..f920ecbd Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png b/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png new file mode 100644 index 00000000..76eddd3e Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_background.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..01b0f78d Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.png b/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.png new file mode 100644 index 00000000..55ed816a Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png b/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png new file mode 100644 index 00000000..3f362d7d Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_background.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..9870880f Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.png b/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.png new file mode 100644 index 00000000..488af9e2 Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png b/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png new file mode 100644 index 00000000..9fd0b85d Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_background.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 00000000..69744222 Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.png b/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.png new file mode 100644 index 00000000..10bccebe Binary files /dev/null and b/wifecraft/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.png differ diff --git a/wifecraft/branding/header.jpg b/wifecraft/branding/header.jpg new file mode 100644 index 00000000..2fd14ca7 Binary files /dev/null and b/wifecraft/branding/header.jpg differ diff --git a/wifecraft/branding/icon.png b/wifecraft/branding/icon.png new file mode 100644 index 00000000..2b8747ba Binary files /dev/null and b/wifecraft/branding/icon.png differ diff --git a/wifecraft/branding/make-icons.py b/wifecraft/branding/make-icons.py new file mode 100644 index 00000000..f3b62956 --- /dev/null +++ b/wifecraft/branding/make-icons.py @@ -0,0 +1,85 @@ +# Builds Wifecraft's launcher icon layers from the user's emblem (icon.png: the blue-violet "W" in +# its ring, on black). The emblem fills the adaptive icon's safe zone on a dark violet ground; +# Android's themed icons get the "W" and its ring in white. +# python3 make-icons.py icon.png ../android/app/src/main/res +import os +import sys + +from PIL import Image, ImageDraw, ImageFilter + +icon_path, out = sys.argv[1], sys.argv[2] +emblem = Image.open(icon_path).convert('RGB') + + +def emblem_rgba(): + """The emblem with its black surround made transparent.""" + e = emblem.convert('RGBA') + px = e.load() + for y in range(e.height): + for x in range(e.width): + r, g, b, a = px[x, y] + v = max(r, g, b) + if v < 40: + px[x, y] = (r, g, b, int(255 * v / 40)) + return e.crop(e.getbbox()) + + +EMBLEM = emblem_rgba() + + +def background(px): + """A dark violet ground, lighter in the middle, like Dalaran's night.""" + img = Image.new('RGB', (px, px), (14, 9, 34)) + glow = Image.new('L', (px, px), 0) + ImageDraw.Draw(glow).ellipse([px * 0.15, px * 0.15, px * 0.85, px * 0.85], fill=120) + glow = glow.filter(ImageFilter.GaussianBlur(px * 0.12)) + img = Image.composite(Image.new('RGB', (px, px), (58, 40, 120)), img, glow) + return img.convert('RGBA') + + +def foreground(px): + """The emblem, inside the 72dp the launcher shows of the 108dp square.""" + img = Image.new('RGBA', (px, px), (0, 0, 0, 0)) + target = int(px * 0.62) + e = EMBLEM.resize((target, target), Image.LANCZOS) + img.alpha_composite(e, ((px - target) // 2, (px - target) // 2)) + return img + + +def monochrome(px): + """The emblem's bright strokes in white, for themed icons.""" + img = Image.new('RGBA', (px, px), (0, 0, 0, 0)) + target = int(px * 0.6) + e = EMBLEM.resize((target, target), Image.LANCZOS) + r, g, b, a = e.split() + lum = Image.eval(Image.merge('RGB', (r, g, b)).convert('HSV').split()[2], lambda v: 255 if v > 175 else 0) + lum = lum.filter(ImageFilter.MedianFilter(5)).filter(ImageFilter.GaussianBlur(0.8)) + white = Image.new('RGBA', e.size, (255, 255, 255, 255)) + img.paste(white, ((px - target) // 2, (px - target) // 2), lum) + return img + + +densities = {'mdpi': 1, 'hdpi': 1.5, 'xhdpi': 2, 'xxhdpi': 3, 'xxxhdpi': 4} +for name, k in densities.items(): + d = os.path.join(out, 'mipmap-' + name) + os.makedirs(d, exist_ok=True) + px = int(108 * k) + background(px).save(os.path.join(d, 'ic_launcher_background.png'), optimize=True) + foreground(px).save(os.path.join(d, 'ic_launcher_foreground.png'), optimize=True) + monochrome(px).save(os.path.join(d, 'ic_launcher_monochrome.png'), optimize=True) + +# Preview: a circle, a rounded square, and themed. +size = 432 +icon = background(size) +icon.alpha_composite(foreground(size)) +preview = Image.new('RGBA', (size * 3 + 80, size + 40), (230, 230, 230, 255)) +circle = Image.new('L', (size, size), 0) +ImageDraw.Draw(circle).ellipse([72, 72, 360, 360], fill=255) +square = Image.new('L', (size, size), 0) +ImageDraw.Draw(square).rounded_rectangle([72, 72, 360, 360], radius=70, fill=255) +preview.paste(icon, (20, 20), circle) +preview.paste(icon, (size + 40, 20), square) +themed = Image.new('RGBA', (size, size), (36, 40, 64, 255)) +themed.alpha_composite(monochrome(size)) +preview.paste(themed, (2 * size + 60, 20), circle) +preview.save(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'preview.png')) diff --git a/wifecraft/branding/preview.png b/wifecraft/branding/preview.png new file mode 100644 index 00000000..93a56cd3 Binary files /dev/null and b/wifecraft/branding/preview.png differ diff --git a/wifecraft/branding/splash.jpg b/wifecraft/branding/splash.jpg new file mode 100644 index 00000000..0e814f7f Binary files /dev/null and b/wifecraft/branding/splash.jpg differ diff --git a/wifecraft/engine-test/boneanim_test.cpp b/wifecraft/engine-test/boneanim_test.cpp new file mode 100644 index 00000000..bd6044d3 --- /dev/null +++ b/wifecraft/engine-test/boneanim_test.cpp @@ -0,0 +1,173 @@ +// Imported animations as the engine plays them (engine/boneanim.h) and the game's own layers (M2Model::isLayer, pose over a +// base), without GL. Build: engine-test/build.sh; run: build/boneanim_test [FILES_DIR] (exit 0: all pass). With FILES_DIR (the +// downloaded game files, each named by its id) the night elf woman (921844, her skeleton and .anim files) is checked too: +// FacePose and HandsClosed are layers, Stand is not, and FacePose played over Stand keeps Stand's arms (not the bind pose). +#include +#include +#include +#include + +#include "../android/app/src/main/cpp/engine/boneanim.h" + +using namespace wc; + +static int failures = 0; +#define CHECK(cond, ...) do { if (!(cond)) { ++failures; std::printf("FAIL %s:%d: ", __FILE__, __LINE__); std::printf(__VA_ARGS__); std::printf("\n"); } } while (0) + +static V3 rotate(const Quat& q, V3 v) { + Quat r = quatMul(quatMul(q, Quat(v.x, v.y, v.z, 0)), quatInv(q)); + return V3(r.x, r.y, r.z); +} +static float angleDeg(V3 a, V3 b) { + float d = a.normalized().dot(b.normalized()); + return std::acos(std::fmax(-1.0f, std::fmin(1.0f, d))) * 57.29578f; +} + +// A small skeleton with the key bone ids findWowBone knows: Root 26, Chest 53, L_Clavicle 2, L_UpperArm 0, L_Forearm 62, +// L_Hand 65, and L_Middle1 (the hand's aim) by its name's CRC. +struct Rig { M2Model m; std::vector names; }; +static Rig rig(V3 clavicle, V3 upperArm, V3 forearm, V3 hand, V3 middle) { + Rig r; + auto add = [&](const char* name, int key, int parent, V3 pivot) { + M2Bone b; b.keyBoneId = key; b.parent = int16_t(parent); b.pivot = pivot; + r.m.bones.push_back(b); r.names.push_back(name); + }; + add("Root", 26, -1, V3(0, 0, 0)); + add("Chest", 53, 0, V3(0, 0, 1.3f)); + add("L_Clavicle", 2, 1, clavicle); + add("L_UpperArm", 0, 2, upperArm); + add("L_Forearm", 62, 3, forearm); + add("L_Hand", 65, 4, hand); + M2Bone mid; mid.parent = 5; mid.pivot = middle; mid.nameCrc = crc32("MiddleFingerL", std::strlen("MiddleFingerL")); + r.m.bones.push_back(mid); r.names.push_back("L_Middle1"); + return r; +} + +static V3 refDir(const char* bone) { + for (const AnimRest& a : kAnimRest) if (std::string(a.bone) == bone) return V3(a.x, a.y, a.z).normalized(); + return V3(0, 0, 1); +} + +int main(int argc, char** argv) { + // 1. Keys: before the first and after the last hold; between, linear; a loop wraps from the last key to the first. + { + std::vector t{0.0f, 1.0f, 2.0f}; + size_t a, b; float f; + boneKeys(t, -1, 0, a, b, f); CHECK(a == 0 && b == 0 && f == 0, "before the first key: %zu %zu %f", a, b, f); + boneKeys(t, 1.5f, 0, a, b, f); CHECK(a == 1 && b == 2 && std::fabs(f - 0.5f) < 1e-6f, "between: %zu %zu %f", a, b, f); + boneKeys(t, 2.5f, 0, a, b, f); CHECK(a == 2 && b == 2 && f == 0, "past the last, no loop: %zu %zu %f", a, b, f); + boneKeys(t, 2.5f, 3.0f, a, b, f); CHECK(a == 2 && b == 0 && std::fabs(f - 0.5f) < 1e-6f, "loop wraps: %zu %zu %f", a, b, f); + boneKeys(t, 2.5f, 2.0f, a, b, f); CHECK(a == 2 && b == 2, "a loop as long as its keys holds the last: %zu %zu", a, b); + std::vector late{0.5f, 1.0f}; + boneKeys(late, 1.5f, 2.0f, a, b, f); CHECK(a == 1 && b == 1, "keys not from 0 don't wrap: %zu %zu", a, b); + std::vector one{0.3f}; + boneKeys(one, 5, 1, a, b, f); CHECK(a == 0 && b == 0 && f == 0, "one key holds"); + std::vector none; + boneKeys(none, 1, 1, a, b, f); CHECK(a == 0 && b == 0, "no keys: no index past the end"); + } + + // 2. The reference rest pose (the bones exactly along kAnimRest): nothing is turned. + { + V3 c(0.0f, 0.06f, 1.35f); + V3 u = c + refDir("L_Clavicle") * 0.15f; + V3 fo = u + refDir("L_UpperArm") * 0.28f; + V3 h = fo + refDir("L_Forearm") * 0.25f; + V3 mid = h + refDir("L_Hand") * 0.08f; + Rig r = rig(c, u, fo, h, mid); + BoneAnim an; + for (const char* n : {"Chest", "L_Clavicle", "L_UpperArm", "L_Forearm", "L_Hand", "L_Middle1"}) + an.tracks.push_back({n, true, {0.0f}, {0.1f, 0.2f, 0.3f, 0.9273618f}}); + CHECK(fitBoneAnim(an, r.m) == 0, "the reference rest pose was turned"); + } + + // 3. Another model's rest pose (shoulders 25 degrees lower, upper arm 15 off): the clip's bind pose, as the importer + // made it for the reference (each bone's world turn Q = arc(reference rest, Sims bind direction), local = inv(parent) Q), + // once fitted, points each of this model's limbs along the Sims bind direction, as on the reference. + { + V3 c(0.0f, 0.06f, 1.35f); + auto tilt = [](V3 d, float deg) { float a = deg / 57.29578f; return V3(d.x, d.y * std::cos(a) - d.z * std::sin(a), d.y * std::sin(a) + d.z * std::cos(a)).normalized(); }; + V3 u = c + tilt(refDir("L_Clavicle"), -25) * 0.15f; + V3 fo = u + tilt(refDir("L_UpperArm"), 15) * 0.28f; + V3 h = fo + tilt(refDir("L_Forearm"), 10) * 0.25f; + V3 mid = h + refDir("L_Hand") * 0.08f; + Rig r = rig(c, u, fo, h, mid); + // the Sims bind directions the clip was made for (any; here a T pose's) + std::vector chain{"L_Clavicle", "L_UpperArm", "L_Forearm", "L_Hand"}; + std::vector sims{V3(0, 1, 0.05f).normalized(), V3(0, 1, 0), V3(0.1f, 1, 0).normalized(), V3(0, 1, -0.1f).normalized()}; + BoneAnim an; + an.tracks.push_back({"Chest", true, {0.0f, 1.0f}, {0, 0, 0, 1, 0, 0, 0, 1}}); + Quat parentWorld; + std::vector worlds; + for (size_t i = 0; i < chain.size(); ++i) { + Quat q = quatArc(refDir(chain[i].c_str()), sims[i]); + Quat local = quatMul(quatInv(parentWorld), q); + // two keys, the second the negation of the first (the same turn): the fit keeps them on one side + an.tracks.push_back({chain[i], true, {0.0f, 1.0f}, {local.x, local.y, local.z, local.w, -local.x, -local.y, -local.z, -local.w}}); + parentWorld = q; + } + an.tracks.push_back({"L_Middle1", true, {0.0f}, {0, 0, 0, 1}}); + int turned = fitBoneAnim(an, r.m); + CHECK(turned >= 4, "the arm's tracks weren't turned (%d)", turned); + // the model's world turns from the fitted locals, down the chain (Chest at identity) + Quat world; + for (size_t i = 0; i < chain.size(); ++i) { + const BoneAnimTrack& t = an.tracks[i + 1]; + world = quatMul(world, Quat(t.values[0], t.values[1], t.values[2], t.values[3])); + int b = r.m.findWowBone(chain[i]); + int aim = r.m.findWowBone(i + 1 < chain.size() ? chain[i + 1] : "L_Middle1"); + V3 rest = r.m.bones[size_t(aim)].pivot - r.m.bones[size_t(b)].pivot; + float off = angleDeg(rotate(world, rest), sims[i]); + CHECK(off < 0.5f, "%s points %.2f degrees from the clip's direction after the fit", chain[i].c_str(), off); + const float* v = &t.values[0]; + CHECK(v[0] * v[4] + v[1] * v[5] + v[2] * v[6] + v[3] * v[7] > 0, "%s's keys flip sign", chain[i].c_str()); + } + // unfitted, the clavicle would have been off by about the 25 degrees + Quat q0 = quatArc(refDir("L_Clavicle"), sims[0]); + V3 rest0 = u - c; + CHECK(angleDeg(rotate(q0, rest0), sims[0]) > 20, "the test's rest pose isn't different enough"); + } + + // 4. The game's files, when given: FacePose (808) and HandsClosed (15) are layers, Stand (0) isn't; FacePose posed + // over Stand keeps Stand's arms and legs, and alone (no base) leaves them at the bind (the arms-out pose it fixes). + if (argc > 1) { + std::string dir = argv[1]; + FileLookup files = [&](uint32_t f) { + std::string p = dir + "/" + std::to_string(f); + FILE* x = std::fopen(p.c_str(), "rb"); + if (!x) return std::string(); + std::fclose(x); + return p; + }; + M2Model m; + if (!m.load(921844, files)) { + std::printf("skipped the game's files: %s\n", m.error.c_str()); + } else { + int stand = m.findSequence(0), face = m.findSequence(808), hands = m.findSequence(15); + for (int s : {stand, face, hands}) if (s >= 0) m.ensureSequence(s, files); + CHECK(stand >= 0 && m.sequenceReady(stand) && !m.isLayer(stand), "Stand is a layer or not here"); + CHECK(face >= 0 && m.isLayer(face), "FacePose isn't a layer"); + CHECK(hands >= 0 && m.isLayer(hands), "HandsClosed isn't a layer"); + if (stand >= 0 && face >= 0) { + std::vector base, over, alone; + m.pose(stand, 500, 500, base, true); + m.pose(face, 100, 500, over, false, &base); + m.pose(face, 100, 500, alone, false); + for (const char* n : {"L_UpperArm", "R_UpperArm", "L_Thigh", "Pelvis"}) { + int b = m.findWowBone(n); + if (b < 0) continue; + const Quat& s = base[size_t(b)].r; const Quat& o = over[size_t(b)].r; const Quat& a = alone[size_t(b)].r; + CHECK(std::fabs(s.x - o.x) + std::fabs(s.y - o.y) + std::fabs(s.z - o.z) + std::fabs(s.w - o.w) < 1e-5f, + "%s over Stand isn't Stand's", n); + CHECK(std::fabs(a.x) + std::fabs(a.y) + std::fabs(a.z) < 1e-5f, "%s of FacePose alone isn't the bind (the test's premise)", n); + } + int keyed = 0; + for (size_t b = 0; b < m.bones.size(); ++b) keyed += m.boneKeyed(int(b), face); + CHECK(keyed * 2 < int(m.bones.size()), "FacePose keys %d of %zu bones", keyed, m.bones.size()); + } + } + } + + if (failures) { std::printf("%d failed\n", failures); return 1; } + std::printf("boneanim_test: all passed\n"); + return 0; +} diff --git a/wifecraft/engine-test/build.sh b/wifecraft/engine-test/build.sh index ee66a6de..8271dcaf 100755 --- a/wifecraft/engine-test/build.sh +++ b/wifecraft/engine-test/build.sh @@ -20,3 +20,9 @@ g++ -std=c++17 -O2 -Wall -Wno-unused-parameter -I"$engine" \ "$here/bodyshape_test.cpp" "$engine/bodyshape.cpp" "$engine/m2.cpp" "$engine/bytes.cpp" \ -o "$here/build/bodyshape_test" echo "$here/build/bodyshape_test" +# Imported animations as the engine plays them (engine/boneanim.h: keys, the loop's wrap, the fit to a model's rest pose) and +# the game's layers (M2Model::isLayer, a layer posed over its base): build/boneanim_test [FILES_DIR], exit 0 when all pass. +g++ -std=c++17 -O2 -Wall -Wno-unused-parameter -I"$engine" \ + "$here/boneanim_test.cpp" "$engine/m2.cpp" "$engine/bytes.cpp" \ + -o "$here/build/boneanim_test" +echo "$here/build/boneanim_test" diff --git a/wifecraft/engine-test/harness.cpp b/wifecraft/engine-test/harness.cpp index a00f38ec..4f4b7224 100644 --- a/wifecraft/engine-test/harness.cpp +++ b/wifecraft/engine-test/harness.cpp @@ -17,6 +17,7 @@ // bonestop N takes it off (Scene::clearBoneAnim) // soft off|subtle|natural|strong Options' Soft body (Scene::setSoftBody; the scene's default: natural) // render OUT.ppm|OUT.png WIDTH HEIGHT TIME_MS +// bonepos N MODEL BONE... prints where those bones' pivots are as person N was last drawn (WoW-side names) // location JSONFILE [ID [VIEW]] a location (Scene::loadLocation; ID chooses the entry, VIEW its light/fog) // view NAME the loaded location's view: its light and fog, and its camera // prop N MODEL X Y Z YAW SCALE an editor prop (Scene::addProp: an M2 or a WMO by file id) @@ -84,6 +85,7 @@ #include #include #include +#include #include #include #include @@ -507,11 +509,12 @@ int main(int argc, char** argv) { std::fprintf(stderr, "GL: %s / %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION)); std::string dir; - Scene scene([&](uint32_t id) { + FileLookup lookup = [&](uint32_t id) { std::string p = dir + "/" + std::to_string(id); struct stat st; return stat(p.c_str(), &st) == 0 ? p : std::string(); - }); + }; + Scene scene(lookup); scene.initGl(); std::map actors, props; Light light; @@ -868,6 +871,24 @@ int main(int argc, char** argv) { Scene::CameraInfo c = scene.cameraInfo(); std::fprintf(stderr, "camera eye %.2f %.2f %.2f target %.2f %.2f %.2f up %.2f %.2f %.2f fov %.1f aspect %.3f\n", c.eye.x, c.eye.y, c.eye.z, c.target.x, c.target.y, c.target.z, c.up.x, c.up.y, c.up.z, c.fovY, c.aspect); + } else if (cmd == "bonepos") { + // bonepos N MODEL BONE...: where each WoW-side bone's pivot is as person N was last drawn (model space) + int name; uint32_t model; ss >> name >> model; + static std::map> models; + auto& mm = models[model]; + if (!mm) { mm = std::make_unique(); if (!mm->load(model, lookup)) std::fprintf(stderr, "bonepos: %s\n", mm->error.c_str()); } + std::vector mats; int seq = -1; uint32_t at = 0; + std::string bone; + if (actors.count(name) && scene.actorPose(actors[name], mats, seq, at)) { + std::printf("bonepos %d seq %d t %u:", name, seq, at); + while (ss >> bone) { + int b = mm->findWowBone(bone); + if (b < 0 || size_t(b) >= mats.size()) { std::printf(" %s=?", bone.c_str()); continue; } + V3 p = mats[size_t(b)].point(mm->bones[size_t(b)].pivot); + std::printf(" %s=(%.3f,%.3f,%.3f)", bone.c_str(), p.x, p.y, p.z); + } + std::printf("\n"); + } } else if (cmd == "render") { std::string out; int w, h; uint32_t t; ss >> out >> w >> h >> t; diff --git a/wifecraft/tools/sounds.py b/wifecraft/tools/sounds.py index 82b9255c..1c7626ef 100644 --- a/wifecraft/tools/sounds.py +++ b/wifecraft/tools/sounds.py @@ -30,13 +30,33 @@ "night": 594369, # sound/ambience/zoneambience/dalarancitynight.ogg } -# The interface's sound kits (the game's SOUNDKIT constants). +# The interface's sound kits (the game's SOUNDKIT constants: Blizzard_SharedXML/Mainline/SoundKitConstants.lua; +# audio/Soundscape.kt's UiSounds keeps the same table). The game's buttons have no hover sound. UI = { - "click": 857, # IG_MAINMENU_OPTION - "open": 850, # IG_MAINMENU_OPEN (the game menu) + "open": 850, # IG_MAINMENU_OPEN (a window) "close": 851, # IG_MAINMENU_CLOSE + "click": 852, # IG_MAINMENU_OPTION (857 is the checkbox-off kit) + "ok": 798, # GS_TITLE_OPTION_OK + "check_on": 856, # IG_MAINMENU_OPTION_CHECKBOX_ON + "check_off": 857, # IG_MAINMENU_OPTION_CHECKBOX_OFF + "tab": 841, # IG_CHARACTER_INFO_TAB + "page": 836, # IG_ABILITY_PAGE_TURN (three files) + "select": 877, # IG_QUEST_LIST_SELECT + "create": 813, # GS_CHARACTER_SELECTION_CREATE_NEW + "begin": 809, # GS_CHARACTER_SELECTION_ENTER_WORLD "gossip": 875, # IG_QUEST_LIST_OPEN (a choice) - "ending": 12891, # UI_ALERT_ACHIEVEMENT_GAINED + "ending": 12891, # achievmentsound1.ogg (the achievement toast's) +} + +# The title's music: MUS_110_MAIN_TITLE (The War Within's main title, mus_110_thewarwithin_maintitle.mp3). +TITLE_KIT = 262929 + +# The places' sound (assets/locations.json's ambience block, from the tables): the Embassy's room (WMOAreaTable 93968) +# has ZoneMusic 1929 (Zone_735_AlliedRace_EmbassyAlliance: kit 97594), the area (9171) SoundAmbience 569: day kit +# 17895, night kit 17896. +PLACES = { + "embassy": {"area": 9171, "zoneMusic": 1929, "ambience": 569, "music_kit": 97594, + "day_kit": 17895, "night_kit": 17896, "silenceMs": [180000, 300000]}, } # Each speaker's voice for the emotes that have one: (race, sex) in EmotesTextSound. @@ -66,7 +86,13 @@ def main(): out = {"music": MUSIC, "ambience": AMBIENCE, "ui": {}, "voices": {}, "effects": {}} for name, kit in UI.items(): - out["ui"][name] = files(kit)[:1] + out["ui"][name] = files(kit) + out["title"] = {"kit": TITLE_KIT, "music": files(TITLE_KIT)} + out["places"] = {} + for pid, p in PLACES.items(): + out["places"][pid] = {"area": p["area"], "zoneMusic": p["zoneMusic"], "ambience": p["ambience"], + "music": files(p["music_kit"]), "ambienceDay": files(p["day_kit"]), + "ambienceNight": files(p["night_kit"]), "silenceMs": p["silenceMs"]} emote_names = {int(r["ID"]): r["Name"].lower() for r in table(d, "EmotesText")} sounds = table(d, "EmotesTextSound") diff --git a/wifecraft/unit-tests/build.gradle.kts b/wifecraft/unit-tests/build.gradle.kts index a3bb3c3c..e7699436 100644 --- a/wifecraft/unit-tests/build.gradle.kts +++ b/wifecraft/unit-tests/build.gradle.kts @@ -37,6 +37,8 @@ val pureUi = tasks.register("pureUi") { from("../android/app/src/main/java/com/logie/wifecraft/ui/ImageCache.kt") // the menus' motion: durations, the reduce-motion switch, the double-tap gate, touch boxes, scroll thumb, list keys (MenuMotion) from("../android/app/src/main/java/com/logie/wifecraft/ui/MenuMotion.kt") + // the live scene's HUD: the action bar's orders and pages, the help line, the clock, the layout, the animation tabs (SceneHud) + from("../android/app/src/main/java/com/logie/wifecraft/ui/SceneHud.kt") into(layout.buildDirectory.dir("gen/pureUi")) } @@ -56,6 +58,8 @@ val purePlay = tasks.register("purePlay") { val pureAudio = tasks.register("pureAudio") { from("../android/app/src/main/java/com/logie/wifecraft/audio/SceneAudioCore.kt") from("../android/app/src/main/java/com/logie/wifecraft/audio/SoundIndex.kt") + // the soundscape's decisions: the mixer, the ducking, the crossfade, which music where, sounds.json (Soundscape) + from("../android/app/src/main/java/com/logie/wifecraft/audio/Soundscape.kt") // the partner animations' sounds folder (resolution, names, hashes, zip import) from("../android/app/src/main/java/com/logie/wifecraft/audio/SoundNames.kt") from("../android/app/src/main/java/com/logie/wifecraft/audio/PartnerSounds.kt") diff --git a/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/anim/ClipValidationTest.kt b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/anim/ClipValidationTest.kt new file mode 100644 index 00000000..0c96e245 --- /dev/null +++ b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/anim/ClipValidationTest.kt @@ -0,0 +1,102 @@ +package com.logie.wifecraft.anim + +import com.logie.wifecraft.sims.Channel +import com.logie.wifecraft.sims.SimsClip +import com.logie.wifecraft.sims.SimsTrack +import org.json.JSONObject +import java.io.File +import java.nio.file.Files +import kotlin.math.cos +import kotlin.math.sin +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class ClipValidationTest { + private fun turn(deg: Double): FloatArray { val h = Math.toRadians(deg) / 2; return floatArrayOf(0f, 0f, sin(h).toFloat(), cos(h).toFloat()) } + private fun rot(bone: String, vararg keys: Pair) = BoneTrack(bone, Channel.ROTATION, + keys.map { it.first }.toFloatArray(), keys.flatMap { turn(it.second).toList() }.toFloatArray()) + private fun anim(duration: Float, vararg tracks: BoneTrack) = Anim("", "c", "", duration, true, tracks.toList(), "s", 0) + + private val good = anim(1f, rot("Chest", 0f to 0.0, 0.5f to 20.0, 1f to 0.0), rot("L_UpperArm", 0f to 0.0, 1f to 30.0), + BoneTrack("Root", Channel.POSITION, floatArrayOf(0f, 1f), floatArrayOf(0f, 0f, 0f, 0.1f, 0f, 0f))) + + @Test fun aSoundClipPasses() = assertNull(ClipValidation.problem(good)) + + @Test fun brokenClipsAreNamed() { + assertNotNull(ClipValidation.problem(anim(1f))) // no tracks + assertNotNull(ClipValidation.problem(anim(1f, rot("L_Index1", 0f to 0.0, 1f to 40.0)))) // fingers only + assertNotNull(ClipValidation.problem(anim(1f, BoneTrack("Chest", Channel.ROTATION, floatArrayOf(0f), floatArrayOf(0f, 0f, Float.NaN, 1f))))) + assertNotNull(ClipValidation.problem(anim(1f, BoneTrack("Chest", Channel.ROTATION, floatArrayOf(0f), floatArrayOf(0f, 0f, 0f, 0f))))) + assertNotNull(ClipValidation.problem(anim(0f, rot("Chest", 0f to 0.0, 0f to 40.0)))) // moves in no time + assertNotNull(ClipValidation.problem(anim(700f, rot("Chest", 0f to 0.0, 700f to 40.0)))) + assertNotNull(ClipValidation.problem(anim(1f, rot("Chest", 0f to 0.0, 5f to 40.0)))) // keys past the end + // a flip: 170 degrees in one 30 fps frame + val flip = ClipValidation.problem(anim(1f, rot("L_Forearm", 0f to 0.0, 0.033f to 170.0, 1f to 170.0))) + assertTrue(flip != null && "L_Forearm" in flip, "$flip") + // the same turn spread over a second is a movement, not a flip + assertNull(ClipValidation.problem(anim(1f, rot("L_Forearm", 0f to 0.0, 1f to 170.0)))) + // a sign flip alone (q then -q, the same turn) is no flip + assertNull(ClipValidation.problem(anim(1f, BoneTrack("Chest", Channel.ROTATION, floatArrayOf(0f, 0.033f), + floatArrayOf(0f, 0f, 0.2588f, 0.9659f, 0f, 0f, -0.2588f, -0.9659f))))) + assertNotNull(ClipValidation.problem(anim(1f, BoneTrack("Root", Channel.POSITION, floatArrayOf(0f, 0.5f), + floatArrayOf(0f, 0f, 0f, 5f, 0f, 0f))))) // a teleport + } + + @Test fun pairsSayWhichActor() { + val bad = anim(1f) + val p = PairAnim("", "p", PairAnim.CATEGORY, good, bad, PairOffset.ZERO, PairOffset.ZERO, true, emptySet(), emptyList(), source = "x", importedAt = 0) + assertTrue(ClipValidation.problem(p)!!.startsWith("Actor B")) + assertNull(ClipValidation.problem(p.copy(b = good))) + } + + /** The import leaves a broken conversion out with its reason, and keeps the rest. */ + @Test fun theImportSkipsBrokenClips() { + val retarget = object : Retarget { + override fun convert(clip: SimsClip): Anim = + if (clip.name == "broken") anim(1f, rot("L_Index1", 0f to 0.0, 1f to 40.0)).copy(name = clip.name) + else good.copy(name = clip.name) + } + val reader: (ByteArray) -> List = { bytes -> + String(bytes).lines().drop(1).filter { it.isNotEmpty() }.map { + SimsClip(it, 1f, listOf(SimsTrack(1, Channel.ROTATION, floatArrayOf(0f), floatArrayOf(0f, 0f, 0f, 1f))), "hash:$it") + } + } + val tmp = Files.createTempDirectory("cv").toFile() + try { + val pkg = "DBPF\nfine\nbroken\n".toByteArray() + val events = ArrayList() + val out = ImportPipeline(retarget, tmp, reader = reader, tuning = { emptyList() }) + .run(listOf(ImportInput("a.package") { pkg.inputStream() })) { events += it } + assertEquals(listOf("fine"), out.map { it.name }) + val skipped = events.filterIsInstance().single() + assertTrue("broken" in skipped.name && "main bones" in skipped.why, "${skipped.name}: ${skipped.why}") + } finally { tmp.deleteRecursively() } + } + + /** The engine's copy of the rest directions (cpp engine/boneanim.h kAnimRest) is the profile's wowRest, aim for aim. */ + @Test fun theEngineRestTableMatchesTheProfile() { + val assets = System.getProperty("wifecraft.assets") ?: return + val header = File(assets, "../cpp/engine/boneanim.h").readText() + val rows = Regex("""\{"(\w+)", "(\w+)", (-?[\d.]+)f, (-?[\d.]+)f, (-?[\d.]+)f\}""").findAll(header) + .associate { m -> m.groupValues[1] to (m.groupValues[2] to List(3) { m.groupValues[3 + it].toFloat() }) } + val profile = JSONObject(File(assets, "sims_profile.json").readText()) + val rest = profile.getJSONObject("wowRest") + val bones = profile.getJSONArray("bones") + var n = 0 + for (i in 0 until bones.length()) { + val b = bones.getJSONObject(i) + val aim = b.optString("aim").ifEmpty { null } ?: continue + val wow = b.getString("wow") + if (!rest.has(wow)) continue + val row = rows[wow] ?: error("boneanim.h has no rest direction for $wow") + assertEquals(aim, row.first, wow) + val dir = rest.getJSONArray(wow) + for (c in 0 until 3) assertEquals(dir.getDouble(c).toFloat(), row.second[c], 1e-4f, wow) + n++ + } + assertEquals(rows.size, n, "boneanim.h has rows the profile doesn't") + } +} diff --git a/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/anim/PipelineTest.kt b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/anim/PipelineTest.kt index a0701cf4..3db7e44d 100644 --- a/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/anim/PipelineTest.kt +++ b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/anim/PipelineTest.kt @@ -30,7 +30,7 @@ class PipelineTest { private val fake = object : Retarget { override fun convert(clip: SimsClip): Anim { if (clip.name == "boom") throw IllegalStateException("no bones matched") - return Anim("", clip.name, "", clip.duration, false, listOf(BoneTrack("Hips", Channel.POSITION, floatArrayOf(0f), floatArrayOf(0f, 0f, 0f))), "", 0) + return Anim("", clip.name, "", clip.duration, false, listOf(BoneTrack("Root", Channel.POSITION, floatArrayOf(0f), floatArrayOf(0f, 0f, 0f))), "", 0) } } diff --git a/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/audio/SoundscapeTest.kt b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/audio/SoundscapeTest.kt new file mode 100644 index 00000000..3c71b61b --- /dev/null +++ b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/audio/SoundscapeTest.kt @@ -0,0 +1,216 @@ +package com.logie.wifecraft.audio + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class SoundscapeTest { + private fun book(): SoundBook { + val dir = System.getProperty("wifecraft.assets") ?: "../android/app/src/main/assets" + return SoundBook.parse(File(dir, "sounds.json").readText()) + } + + // ---- the mixer ---- + + @Test fun mixerMultipliesMasterAndBusOnACurve() { + val m = MixLevels(master = 100, music = 50, ambience = 100, effects = 0, dialog = 80) + assertEquals(0.25f, Mixer.gain(m, Bus.MUSIC), 1e-6f) + assertEquals(1f, Mixer.gain(m, Bus.AMBIENCE), 1e-6f) + assertEquals(0f, Mixer.gain(m, Bus.EFFECTS), 1e-6f) + assertEquals(0f, Mixer.gain(m, Bus.UI), 1e-6f) // the interface's clicks follow Sound effects + assertEquals(0.64f, Mixer.gain(m, Bus.DIALOG), 1e-6f) + assertEquals(0.25f * 0.25f, Mixer.gain(m.copy(master = 50), Bus.MUSIC), 1e-6f) + } + + @Test fun disabledSoundOrZeroMasterSilencesEverything() { + for (b in Bus.entries) { + assertEquals(0f, Mixer.gain(MixLevels(enabled = false), b)) + assertEquals(0f, Mixer.gain(MixLevels(master = 0), b)) + } + } + + @Test fun duckTouchesOnlyTheBeds() { + val m = MixLevels(master = 100, music = 100, ambience = 100, effects = 100, dialog = 100) + assertEquals(0.5f, Mixer.gain(m, Bus.MUSIC, duck = 0.5f), 1e-6f) + assertEquals(0.5f, Mixer.gain(m, Bus.AMBIENCE, duck = 0.5f), 1e-6f) + assertEquals(1f, Mixer.gain(m, Bus.DIALOG, duck = 0.5f), 1e-6f) + assertEquals(1f, Mixer.gain(m, Bus.EFFECTS, duck = 0.5f), 1e-6f) + } + + @Test fun outOfRangeSlidersAreClamped() { + assertEquals(1f, Mixer.curve(150)); assertEquals(0f, Mixer.curve(-5)) + } + + @Test fun sceneVolumesComeOutAtTheMixersGains() { + val m = MixLevels(master = 80, music = 60, ambience = 40, effects = 90, dialog = 70) + val v = Mixer.sceneVolumes(m) + assertEquals(Mixer.gain(m, Bus.MUSIC), v.music, 1e-6f) + assertEquals(Mixer.gain(m, Bus.EFFECTS), v.effects, 1e-6f) + assertEquals(Mixer.gain(m, Bus.DIALOG), v.voices, 1e-6f) + // SceneAudioCore plays the ambience at ambience x effects + assertEquals(Mixer.gain(m, Bus.AMBIENCE), v.ambience * v.effects, 1e-6f) + assertEquals(0f, Mixer.sceneVolumes(m.copy(effects = 0)).ambience) + } + + // ---- ducking ---- + + @Test fun duckerDipsWhileAVoicePlaysAndComesBackSlower() { + val d = Ducker(depth = 0.4f, attackMs = 100, releaseMs = 400) + assertFalse(d.step(50)) + d.voiceStarted() + d.step(50); assertEquals(0.7f, d.level, 1e-5f) + d.step(50); assertEquals(0.4f, d.level, 1e-5f) + d.step(500); assertEquals(0.4f, d.level, 1e-5f) + assertEquals(0.7f, d.ambienceLevel, 1e-5f) // the ambience dips half as far + d.voiceStarted(); d.voiceEnded() + assertEquals(0.4f, d.target) // one voice still speaking + d.voiceEnded() + d.step(100); assertEquals(0.55f, d.level, 1e-5f) // back up over 400 ms + d.step(1000); assertEquals(1f, d.level); assertFalse(d.moving) + d.voiceEnded(); assertEquals(0, d.voices) // never below none + d.setVoices(3); assertEquals(0.4f, d.target) + } + + // ---- the crossfade ---- + + @Test fun crossfadeFadesTheOldDeckOutAndTheNewIn() { + val x = Crossfader() + val a = x.play(1, fadeInMs = 100) + x.step(50); assertEquals(0.5f, a.level, 1e-5f); assertTrue(x.busy) + x.step(60); assertEquals(1f, a.level); assertFalse(x.busy) + val b = x.play(2, fadeInMs = 200, fadeOutMs = 100) + assertEquals(b, x.current) + assertTrue(a.fadingOut) + assertTrue(x.step(50).isEmpty()) + assertEquals(0.5f, a.level, 1e-5f); assertEquals(0.25f, b.level, 1e-5f) + val gone = x.step(50) + assertEquals(listOf(a.id), gone.map { it.id }) // released once silent + assertEquals(listOf(b.id), x.decks.map { it.id }) + x.step(100); assertEquals(1f, b.level) + } + + @Test fun crossfadeStopEndAndInstantFades() { + val x = Crossfader() + val a = x.play(1, fadeInMs = 0) + assertEquals(1f, a.level); assertFalse(x.busy) + x.stop(0) + assertNull(x.current) + assertEquals(listOf(a.id), x.step(1).map { it.id }) + val b = x.play(2, 100) + assertEquals(b.id, x.end(b.id)?.id) // finished by itself + assertTrue(x.decks.isEmpty()); assertNull(x.end(99)) + x.play(3, 100); x.play(4, 100) + assertEquals(2, x.clear().size); assertTrue(x.decks.isEmpty()) + } + + @Test fun aQuickSecondChangeLeavesOnlyTheNewestPlaying() { + val x = Crossfader() + x.play(1, 100); x.step(100) + x.play(2, 100); x.step(30) + val c = x.play(3, 100) + x.step(1000) + assertEquals(listOf(c.id), x.decks.map { it.id }) + } + + // ---- which music ---- + + @Test fun placeMusicGapIsCutFromTheTablesMinutes() { + val r = MusicPicker.gap(180_000 to 300_000) + assertEquals(MusicPicker.MAX_GAP_MS..MusicPicker.MAX_GAP_MS, r) + assertEquals(MusicPicker.MIN_GAP_MS..MusicPicker.MIN_GAP_MS, MusicPicker.gap(0 to 0)) + assertEquals(6_000L..9_000L, MusicPicker.gap(6_000 to 9_000)) + assertEquals(9_000L..9_000L, MusicPicker.gap(9_000 to 2_000)) // never backwards + repeat(20) { val g = MusicPicker.gapMs(6_000L..9_000L, it.toLong()); assertTrue(g in 6_000L..9_000L) } + } + + @Test fun orderNeverRepeatsATrackBackToBack() { + val tracks = listOf(1, 2, 3, 4, 5, 6) + for (seed in 0L until 40L) { + val played = (0 until 60).map { MusicPicker.at(tracks, seed, it)!! } + for (i in 1 until played.size) assertNotEquals(played[i - 1], played[i], "seed $seed at $i") + for (round in 0 until 10) assertEquals(tracks.toSet(), played.subList(round * 6, round * 6 + 6).toSet()) + } + assertEquals(listOf(7), MusicPicker.order(listOf(7), 1, 3)) + assertNull(MusicPicker.at(emptyList(), 1, 0)) + assertEquals(MusicPicker.at(tracks, 9, 13), MusicPicker.at(tracks, 9, 13)) // the same seed, the same play + } + + @Test fun theEmbassyPlaysItsRoomsZoneMusicAndAmbienceByDayAndNight() { + val b = book() + val p = assertNotNull(b.places["embassy"]) + assertEquals(9171, p.areaId); assertEquals(1929, p.zoneMusic) + val day = assertNotNull(MusicPicker.place(p, night = false)) + val night = assertNotNull(MusicPicker.place(p, night = true)) + // ZoneMusic 1929 (Zone_735_AlliedRace_EmbassyAlliance) -> kit 97594's six files; SoundAmbience 569 -> 17895 / 17896 + assertEquals(listOf(53205, 53206, 53208, 441767, 1417244, 1417249), day.tracks.sorted()) + assertEquals(listOf(539127), day.ambience) + assertEquals(listOf(539080), night.ambience) + assertNotEquals(day.key, night.key) + assertFalse(day.loop) + assertEquals(MusicPicker.MAX_GAP_MS, day.gapMs.first) + } + + @Test fun aPlaceWithoutSoundGivesNoBedAndOneSideFallsBackToTheOther() { + val none = PlaceSound("x", 1, 0, emptyList(), emptyList(), emptyList(), 0 to 0) + assertNull(MusicPicker.place(none, false)) + val dayOnly = none.copy(ambienceDay = listOf(5)) + assertEquals(listOf(5), MusicPicker.place(dayOnly, night = true)!!.ambience) + } + + @Test fun titleMusicIsTheWarWithinsMainTitleLooped() { + val t = MusicPicker.title(book()) + assertEquals("title", t.key) + assertTrue(t.loop) + assertEquals(listOf(6075186), t.tracks) // MUS_110_MAIN_TITLE (kit 262929): mus_110_thewarwithin_maintitle.mp3 + assertTrue(t.ambience.isEmpty()) + } + + // ---- retries ---- + + @Test fun retriesBackOffAndLevelOff() { + assertEquals(0L, RetryPolicy.delayMs(0)) + val d = (1..8).map { RetryPolicy.delayMs(it) } + for (i in 1 until d.size) assertTrue(d[i] >= d[i - 1]) + assertEquals(120_000L, d.last()) + } + + // ---- the interface's sounds ---- + + @Test fun everyUiSoundNameHasItsKitsFilesInSoundsJson() { + val b = book() + // the files SoundKitEntry gives each kit (wago.tools' 12.1.7 tables, checked when the table was made: tools/sounds.py) + val expected = mapOf( + "open" to listOf(567490), "close" to listOf(567464), "click" to listOf(567481), "ok" to listOf(567407), + "check_on" to listOf(567407), "check_off" to listOf(567407), "tab" to listOf(567422), + "page" to listOf(567457, 567472, 567502), "select" to listOf(567508), "create" to listOf(567437), + "begin" to listOf(567419), "gossip" to listOf(567504), "ending" to listOf(569143), + ) + assertEquals(UiSounds.KITS.keys, b.ui.keys) + for ((name, files) in expected) assertEquals(files, b.ui[name]?.sorted(), name) + assertEquals(852, UiSounds.KITS.getValue("click").second) // IG_MAINMENU_OPTION, not the checkbox's 857 + assertEquals(850, UiSounds.KITS.getValue("open").second) + assertEquals(851, UiSounds.KITS.getValue("close").second) + } + + @Test fun unknownUiNamesFallBackOrStaySilent() { + val have = setOf("click", "open") + assertEquals("open", UiSounds.resolve("open", have)) + assertEquals("click", UiSounds.resolve("tab", have)) // a kit not fetched yet: the plain click + assertNull(UiSounds.resolve("hover", have)) // the game's buttons have none + assertNull(UiSounds.resolve("nonsense", have)) + assertNull(UiSounds.resolve("tab", emptySet())) + } + + @Test fun soundBookReadsEveryShortSound() { + val b = book() + assertTrue(b.shortFiles.containsAll(b.ui.values.flatten())) + assertTrue(b.music.isNotEmpty()) + val parsed = SoundBook.parse("""{"ui":{"click":[1]}}""") + assertTrue(parsed.places.isEmpty()); assertTrue(parsed.title.isEmpty()); assertEquals(setOf(1), parsed.shortFiles) + } +} diff --git a/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/catalog/EmotePlayabilityTest.kt b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/catalog/EmotePlayabilityTest.kt new file mode 100644 index 00000000..74a6d87d --- /dev/null +++ b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/catalog/EmotePlayabilityTest.kt @@ -0,0 +1,79 @@ +package com.logie.wifecraft.catalog + +import com.logie.wifecraft.creator.Sex +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class EmotePlayabilityTest { + private val small = """ + {"text":[[60,"Laugh",70,0],[85,"Sigh",-1,0]], + "npc":[], + "anims":{"0":"Stand","69":"EmoteDance","70":"EmoteLaugh","91":"Mount","808":"FacePose","15":"HandsClosed", + "42":"Swim","135":"Fly","1066":"FlyingKick","97":"SitGround","1":"Death","114":"KneelStart"}, + "models":{"1:1":{"m":2,"f":1000764,"a":[0,1,69,1,70,1,91,1,808,1,15,1,42,1,135,1,1066,1,97,1,1,1,114,1],"v":{"85":[13]}}}} + """.trimIndent() + + @Test fun problemsAreSaidPlainly() { + assertNotNull(EmotePlayability.problem(91, "Mount")) + assertNotNull(EmotePlayability.problem(5000, "MountSelfIdle")) + assertNotNull(EmotePlayability.problem(5001, "ReclinedMountPassenger")) + assertNotNull(EmotePlayability.problem(135, "Fly")) + assertNotNull(EmotePlayability.problem(42, "Swim")) + assertNotNull(EmotePlayability.problem(808, "FacePose")) + assertNotNull(EmotePlayability.problem(15, null)) // a layer by id, whatever its name + assertNotNull(EmotePlayability.problem(-1, null)) + assertNull(EmotePlayability.problem(1066, "FlyingKick")) // a monk's kick on the ground, not flight + assertNull(EmotePlayability.problem(69, "EmoteDance")) + assertNull(EmotePlayability.problem(9999, null)) // unnamed: kept + } + + @Test fun thePickerListsOnlyWhatPlaysAlone() { + val c = EmoteCatalog.parse(small) + val all = c.forModel(1, Sex.FEMALE) + val ok = c.playableForModel(1, Sex.FEMALE) + val anims = ok.map { it.anim }.toSet() + assertTrue(91 !in anims && 42 !in anims && 135 !in anims && 15 !in anims && 808 !in anims, "$anims") + assertTrue(69 in anims && 70 in anims && 1066 in anims && 0 in anims) + assertTrue(ok.any { it.id == 85 && it.anim == -1 }, "voice-only kept by default") + assertFalse(c.playableForModel(1, Sex.FEMALE, includeVoiceOnly = false).any { it.anim < 0 }) + assertEquals(all.filter { it in ok }, ok, "the order is kept") + assertEquals(emptyList(), c.playableForModel(99, Sex.MALE)) + } + + @Test fun loopsAndStatesAreHeldByDefault() { + val e = EmoteCatalog.parse(small).forModel(1, Sex.FEMALE).associateBy { it.anim } + assertTrue(e.getValue(0).loop, "Stand") + assertTrue(e.getValue(69).loop, "a dance played once froze on its last frame") + assertTrue(e.getValue(97).loop, "SitGround") + assertFalse(e.getValue(1).loop, "Death holds its last frame") + assertFalse(e.getValue(114).loop, "KneelStart") + assertFalse(e.getValue(70).loop, "the text emote's own (one-shot) is kept") + for (n in listOf("ReadyUnarmed", "HoldBow", "WAGuardStand01", "EmoteReadLoop", "ChannelCastOmni", "StealthWalk", "Monk2HLIdle")) + assertTrue(EmotePlayability.heldByName(n), n) + for (n in listOf("Attack1H", "EmoteWave", "SitGroundDown", "SleepUp", "WADead01", "UseStandingStart", "Knockdown", "SpellCastOmni")) + assertFalse(EmotePlayability.heldByName(n), n) + assertEquals("Combat", EmoteCatalog.categoryOf("FlyingKick")) + assertEquals("Flying", EmoteCatalog.categoryOf("FlyStand")) + } + + /** The app's emotes.json: every creator model's list loses its mounts, flight, swimming and layers, keeps its dances. */ + @Test fun theRealCatalog() { + val dir = System.getProperty("wifecraft.assets") ?: return + val c = EmoteCatalog.parse(File(dir, "emotes.json").readText()) + assertTrue(c.keys.size >= 40) + for (k in c.keys) { + val (race, sex) = k.split(':').map { it.toInt() } + val s = if (sex == 0) Sex.MALE else Sex.FEMALE + val ok = c.playableForModel(race, s) + val names = ok.mapNotNull { if (it.anim >= 0) c.animName(it.anim) else null } + assertTrue(names.none { "Mount" in it || it.startsWith("Swim") || it == "Fly" || it == "FacePose" || it == "HandsClosed" }, "$k: $names") + assertTrue(ok.any { it.anim == 69 }, "$k keeps its dance") + assertTrue(ok.size >= c.forModel(race, s).size - 80, "$k: too much removed") + } + } +} diff --git a/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/simulation/ChatterTest.kt b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/simulation/ChatterTest.kt new file mode 100644 index 00000000..10615aec --- /dev/null +++ b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/simulation/ChatterTest.kt @@ -0,0 +1,287 @@ +package com.logie.wifecraft.simulation + +import com.logie.wifecraft.story.CameraPose +import com.logie.wifecraft.story.Vec3 +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** The NPCs' small talk: the lines (Chatter), a conversation's clock, the simulation's conversations, the bubbles' layout. */ +class ChatterTest { + private val speakers = mapOf( + "a" to Speaker("Nyrelle Moonquill", 4, true), + "b" to Speaker("Bram Ironstock", 3, false), + "c" to Speaker("Someone"), + ) + + private fun chatter() = Chatter(speakers, "Stormwind Embassy") + + @Test fun theSameSeedSaysTheSameThings() { + val one = chatter(); val two = chatter() + val r1 = Random(42); val r2 = Random(42) + repeat(10) { assertEquals(one.conversation("a", "b", r1), two.conversation("a", "b", r2)) } + } + + @Test fun aConversationGreetsTalksAndSaysGoodbye() { + val c = chatter() + val random = Random(3) + repeat(40) { + val lines = c.conversation("a", "b", random) + assertEquals(0, lines[0].speaker) + assertEquals(1, lines[1].speaker) + assertTrue(lines.size in 8..22, "${lines.size} lines") + assertTrue(lines[lines.size - 1].speaker != lines[lines.size - 2].speaker) + for (l in lines) { + assertFalse('{' in l.text || "null" in l.text, l.text) + assertTrue(l.text.isNotBlank()) + if (l.nod) assertEquals(Gestures.TALK, l.gesture) + } + } + } + + @Test fun nothingIsSaidAgainInTheNextConversation() { + val c = chatter() + val random = Random(11) + var last = emptySet() + repeat(30) { + // short prompts ("And?", "Why?") may come again; every real line is new + val lines = c.conversation("a", "b", random).map { it.text }.filter { it.length > 10 } + assertEquals(lines.size, lines.toSet().size, "a line repeated within one conversation: $lines") + assertTrue(lines.none { it in last }, "repeated from the last conversation: ${lines.filter { it in last }}") + last = lines.toSet() + } + } + + @Test fun itIsVariedAndUsesTheirNamesAndPlace() { + val c = chatter() + val random = Random(5) + val all = (0 until 25).flatMap { c.conversation(if (it % 2 == 0) "a" else "b", if (it % 2 == 0) "b" else "a", random) }.map { it.text } + assertTrue(all.toSet().size > 120, "only ${all.toSet().size} different lines") + assertTrue(all.any { "Nyrelle" in it } && all.any { "Bram" in it }) + assertTrue(all.none { "Moonquill" in it }, "the first name only") + val gestures = (0 until 25).flatMap { c.conversation("a", "b", random) }.map { it.gesture }.toSet() + assertTrue(setOf(Gestures.TALK, Gestures.QUESTION, Gestures.LAUGH, Gestures.WAVE).all { it in gestures }) + } + + @Test fun slotsThatCantBeFilledAreNotUsed() { + val c = chatter() + val nobody = Speaker("Someone") + assertNull(c.fill("Do you miss {yourhome}?", speakers.getValue("a"), nobody)) + assertNull(c.fill("Hail, {kin}.", speakers.getValue("a"), nobody)) + assertEquals("Do you miss Ironforge?", c.fill("Do you miss {yourhome}?", speakers.getValue("a"), speakers.getValue("b"))) + assertEquals("Hail, sister.", c.fill("Hail, {kin}.", speakers.getValue("b"), speakers.getValue("a"))) + val random = Random(9) + repeat(20) { for (l in c.conversation("c", "c", random)) assertFalse('{' in l.text) } + assertEquals("the Stormwind Embassy", Chatter.placeRef("Stormwind Embassy")) + assertEquals("Dalaran's streets", Chatter.placeRef("Dalaran's streets")) + assertEquals("the Violet Citadel's terrace", Chatter.placeRef("The Violet Citadel's terrace")) + assertTrue(c.sayings("a").contains("Busy day at the Stormwind Embassy.")) + } + + @Test fun aConversationsClockRunsItsLinesWithGesturesAndNods() { + val lines = listOf( + ChatLine(0, "Hello there, friend.", Gestures.WAVE), + ChatLine(1, "A fine day for it, wouldn't you say so?", Gestures.QUESTION), + ChatLine(0, "It is.", Gestures.TALK, nod = true), + ) + val c = Conversation(lines) + assertEquals(-1, c.gesture(0)) + assertEquals(0, c.start()) + assertEquals(Gestures.WAVE, c.gesture(0)) + assertEquals(Gestures.STAND, c.gesture(1)) + val begun = ArrayList() + var t = 0f + val dt = 1f / 60f + var nodded = false + var talkedAfterWave = false + while (!c.done) { + val i = c.advance(dt) + if (i >= 0) begun += i + if (c.line?.speaker == 0 && c.index == 0 && c.gesture(0) == Gestures.TALK) talkedAfterWave = true + if (c.index == 2 && c.gesture(1) == Gestures.YES) nodded = true + t += dt + check(t < 60f) + } + assertEquals(listOf(1, 2), begun) + assertTrue(talkedAfterWave) + assertTrue(nodded) + val expected = lines.sumOf { Reading.seconds(it.text).toDouble() } + 3 * Conversation.PAUSE + assertEquals(expected, t.toDouble(), 0.1) + assertEquals(-1, c.gesture(0)) + assertNull(c.line) + } + + @Test fun readingTimeGrowsWithTheLine() { + assertEquals(Reading.MIN_READ, Reading.seconds("Hi.")) + assertTrue(Reading.seconds("x".repeat(60)) > Reading.seconds("x".repeat(30))) + assertEquals(Reading.MAX_READ, Reading.seconds("x".repeat(400))) + assertEquals(Gestures.QUESTION, Gestures.of("Anyone for a drink?")) + assertEquals(Gestures.LAUGH, Gestures.of("Ha! That's a good one.")) + assertEquals(Gestures.EXCLAIM, Gestures.of("Hello there!")) + assertEquals(Gestures.TALK, Gestures.of("I could use a rest.")) + } + + // ---- the simulation + + private val step = 1f / 60f + + private fun sim(ids: List, chance: Float = 1f, partner: Float = 0f, seed: Int = 7) = + SceneSimulation(ids, emptySet(), Random(seed), wanderOnly = true, partnerChance = partner, + chatterChance = chance, chatter = chatter()) + + @Test fun idleNpcsGoAndTalkInTurnsThenParting() { + val sim = sim(listOf("a", "b")) + var n = 0 + while (!sim.talking("a")) { sim.tick(step); check(++n < 20_000) } + assertEquals("b", sim.talkingWith("a")) + assertEquals("a", sim.talkingWith("b")) + val said = ArrayList>() + var speaker: String? = null + while (sim.talking("a")) { + sim.tick(step) + for (id in listOf("a", "b")) sim.speech(id)?.let { text -> + if (said.lastOrNull()?.second != text) { said += id to text; speaker = id } + } + assertFalse(sim.speech("a") != null && sim.speech("b") != null, "both talk at once") + check(++n < 200_000) + } + assertNotNull(speaker) + assertTrue(said.size >= 8, "$said") + // they take turns (an exchange's three parts alternate too), and the bubbles are down at the end + for (i in 1 until said.size) assertTrue(said[i].first != said[i - 1].first, "$said") + sim.tick(step) + assertNull(sim.speech("a")); assertNull(sim.speech("b")) + assertFalse(sim.talking("b")) + // they don't start again at once + repeat((SceneSimulation.MIN_CHAT_COOLDOWN / step).toInt() - 60) { sim.tick(step); assertFalse(sim.talking("a")) } + } + + @Test fun theyFaceEachOtherAndGestureWhileTalking() { + val sim = sim(listOf("a", "b")) + var n = 0 + while (sim.speech("a") == null && sim.speech("b") == null) { sim.tick(step); check(++n < 20_000) } + val pa = Pose().also { sim.pose(0, it) } + val pb = Pose().also { sim.pose(1, it) } + assertTrue(pa.gesture >= 0 && pb.gesture >= 0) + val toB = kotlin.math.atan2(pb.y - pa.y, pb.x - pa.x) + assertEquals(0f, kotlin.math.abs(kotlin.math.sin((pa.facing - toB) / 2)), 0.05f) + assertEquals(0f, kotlin.math.abs(kotlin.math.cos((pb.facing - toB) / 2)), 0.05f) + } + + @Test fun anNpcIsNeverInAConversationAndAPartnerAnimationAtOnce() { + val ids = listOf("a", "b", "c", "d") + val sim = sim(ids, chance = 0.6f, partner = 0.6f, seed = 3) + var talks = 0; var pairs = 0 + repeat(60 * 400) { + sim.tick(step) + for (id in ids) { + val talking = sim.talking(id) + val pairing = sim.partnerOf(id) != null + assertFalse(talking && pairing, "$id in both") + if (talking) talks++ + if (pairing) pairs++ + } + } + assertTrue(talks > 0 && pairs > 0) + } + + @Test fun anOrderCutsAConversationShortAndItsBubblesComeDown() { + val sim = sim(listOf("a", "b")) + var n = 0 + while (sim.speech("a") == null && sim.speech("b") == null) { sim.tick(step); check(++n < 20_000) } + assertTrue(sim.walk("a", Vec3(3f, 3f, 0f))) + assertFalse(sim.talking("a")); assertFalse(sim.talking("b")) + assertNull(sim.speech("a")); assertNull(sim.speech("b")) + } + + @Test fun thePlayersChatHasWordsAndSayShowsABubble() { + val sim = sim(listOf("a", "b"), chance = 0f) + assertTrue(sim.chat("a", "b")) + assertTrue(sim.talking("a")) + var n = 0 + while (sim.speech("a") == null) { sim.tick(step); check(++n < 20_000) } + assertTrue(sim.say("b", "Hello there!")) + assertEquals("Hello there!", sim.speech("b")) + assertFalse(sim.say("b", " ")) + val off = sim(listOf("x", "y"), chance = 0f) + assertTrue(off.say("x", "Anyone for a drink?")) + assertEquals(Gestures.TALK, Pose().also { off.pose(0, it) }.gesture) + repeat(((Reading.seconds("Anyone for a drink?") + 0.1f) / step).toInt()) { off.tick(step) } + assertNull(off.speech("x")) + assertEquals(-1, Pose().also { off.pose(0, it) }.gesture) + } + + @Test fun noChatterNoTalk() { + val sim = SceneSimulation(listOf("a", "b"), emptySet(), Random(1), wanderOnly = true) + repeat(60 * 120) { sim.tick(step); assertFalse(sim.talking("a")) } + } + + @Test fun theLiveSceneSaysWhoSpeaksAndGestures() { + val live = LiveScene(listOf("a", "b"), emptySet(), emptyMap(), CameraPose(Vec3(0f, -5f, 2f), Vec3(0f, 0f, 1f), 50f), + 0f, 0f, 0f, 0f, Random(4), wanderOnly = true, chatter = chatter(), chatterChance = 1f) + live.running = true + val speeches = ArrayList>() + val gestures = ArrayList>() + val sink = object : LiveScene.Sink { + override fun camera(eyeX: Float, eyeY: Float, eyeZ: Float, atX: Float, atY: Float, atZ: Float, fov: Float) {} + override fun place(index: Int, x: Float, y: Float, z: Float, facing: Float, furniture: SceneObject?, sx: Float, sy: Float, sz: Float) {} + override fun activity(index: Int, activity: Activity) {} + override fun speech(index: Int, text: String?, id: Long) { speeches += index to text } + override fun gesture(index: Int, animation: Int) { gestures += index to animation } + } + var now = 0L + repeat(60 * 90) { now += 16_666_667L; live.frame(now, sink) {} } + assertTrue(speeches.count { it.second != null } >= 4, "$speeches") + assertTrue(speeches.any { it.first == 0 && it.second != null } && speeches.any { it.first == 1 && it.second != null }) + assertTrue(gestures.any { it.second == Gestures.STAND } && gestures.any { it.second != Gestures.STAND }) + } + + // ---- the bubbles' layout + + @Test fun theTargetIsTheMiddleOfTheViewAndWhatIsBehindIsOff() { + val out = FloatArray(4) + SpeechLayout.project(0f, -10f, 2f, 0f, 0f, 2f, 50f, 800f, 400f, 0f, 0f, 2f, out, 0) + assertEquals(400f, out[0], 0.5f); assertEquals(200f, out[1], 0.5f); assertEquals(10f, out[2], 0.01f) + // higher is further up the screen, to the right (+x when looking down +y) is right + SpeechLayout.project(0f, -10f, 2f, 0f, 0f, 2f, 50f, 800f, 400f, 1f, 0f, 3f, out, 0) + assertTrue(out[0] > 400f && out[1] < 200f) + SpeechLayout.project(0f, -10f, 2f, 0f, 0f, 2f, 50f, 800f, 400f, 0f, -20f, 2f, out, 0) + assertEquals(0f, out[2]) + SpeechLayout.project(0f, -10f, 2f, 0f, 0f, 2f, 50f, 800f, 400f, 50f, 0f, 2f, out, 0) + assertEquals(0f, out[2], "far off to the side") + } + + @Test fun onlyTheNearestSpeakersOnScreenGetBubbles() { + val n = 6 + val layout = FloatArray(n * SpeechLayout.STRIDE) + val depths = floatArrayOf(5f, 3f, 0f, 9f, 4f, 7f) + for (i in 0 until n) layout[i * SpeechLayout.STRIDE + 2] = depths[i] + val speaking = booleanArrayOf(true, true, true, true, true, false) + SpeechLayout.choose(n, speaking, layout, max = 3) + val shown = (0 until n).filter { layout[it * SpeechLayout.STRIDE + 3] == 1f } + assertEquals(listOf(0, 1, 4), shown) + assertTrue(SpeechLayout.head(2f, sitting = true, lying = false) < 2f) + } + + // ---- who is controlled and who is their partner + + @Test fun tappingAnotherNpcWhileControllingOneMakesItThePartner() { + var c = SceneControl() + c = c.tapNpc("a") + assertEquals(SceneControl("a", null), c) + c = c.tapNpc("b") + assertEquals(SceneControl("a", "b"), c) + assertEquals(c, c.tapNpc("a"), "tapping the controlled one changes nothing") + assertEquals(SceneControl("a", "c"), c.tapNpc("c")) + assertEquals(SceneControl("a", null), c.tapNpc("b"), "the partner again clears it") + assertEquals(SceneControl("a", null), c.clearPartner()) + assertEquals(SceneControl("b", null), c.tapCast("b"), "the cast bar switches who is controlled") + assertEquals(SceneControl(), c.tapCast("a")) + assertEquals(SceneControl("a", null), c.keep(listOf("a"))) + assertEquals(SceneControl(), c.keep(listOf("b"))) + } +} diff --git a/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/ui/FrontLayoutTest.kt b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/ui/FrontLayoutTest.kt new file mode 100644 index 00000000..c66a9f79 --- /dev/null +++ b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/ui/FrontLayoutTest.kt @@ -0,0 +1,47 @@ +package com.logie.wifecraft.ui + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class FrontLayoutTest { + @Test fun titleFitsTheFoldsScreens() { + val inner = FrontLayout.title(832f, 750f) + assertFalse(inner.centered); assertFalse(inner.compact) + val coverStanding = FrontLayout.title(411f, 960f) + assertTrue(coverStanding.centered) + val coverLying = FrontLayout.title(960f, 411f) + assertTrue(coverLying.compact); assertFalse(coverLying.centered) + for (l in listOf(inner, coverStanding, coverLying, FrontLayout.title(320f, 480f))) { + assertTrue(l.buttonW <= FrontLayout.BUTTON_MAX) + assertTrue(l.buttonW >= 0f) + } + assertTrue(coverStanding.buttonW + 2 * coverStanding.padH <= 411f) + assertEquals(0f, FrontLayout.title(10f, 10f).buttonW) + } + + @Test fun narrowRowsStackAndManyTabsScroll() { + assertTrue(FrontLayout.sliderStacked(300f)); assertFalse(FrontLayout.sliderStacked(500f)) + assertFalse(FrontLayout.tabsScroll(600f, 3)); assertTrue(FrontLayout.tabsScroll(250f, 3)); assertFalse(FrontLayout.tabsScroll(100f, 0)) + } + + @Test fun backdropDriftIsSmoothBoundedAndStillWhenReduced() { + assertEquals(Triple(1f, 0f, 0f), FrontMotion.drift(0.37f, reduced = true)) + val start = FrontMotion.drift(0f, false); val end = FrontMotion.drift(1f, false) + assertEquals(start.first, end.first, 1e-5f) // loops without a jump + for (i in 0..100) { + val (s, x, y) = FrontMotion.drift(i / 100f, false) + assertTrue(s in 1f..1f + FrontMotion.DRIFT_SCALE + 1e-5f) + assertTrue(kotlin.math.abs(x) <= FrontMotion.DRIFT_PAN + 1e-5f && kotlin.math.abs(y) <= FrontMotion.DRIFT_PAN) + } + } + + @Test fun motesStayOnScreenAndAreStable() { + for (i in 0 until FrontMotion.MOTES) for (p in 0..20) { + val (x, y, a) = FrontMotion.mote(i, p / 20f) + assertTrue(x in 0f..1f, "x $x"); assertTrue(y in -0.1f..1.1f, "y $y"); assertTrue(a in 0f..1f) + } + assertEquals(FrontMotion.mote(3, 0.4f), FrontMotion.mote(3, 0.4f)) + } +} diff --git a/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/ui/SceneHudTest.kt b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/ui/SceneHudTest.kt new file mode 100644 index 00000000..c9cbe33c --- /dev/null +++ b/wifecraft/unit-tests/src/test/kotlin/com/logie/wifecraft/ui/SceneHudTest.kt @@ -0,0 +1,77 @@ +package com.logie.wifecraft.ui + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SceneHudTest { + @Test + fun ordersStartWithTheEverydayOnesAndPartnerOnlyWithAPartner() { + val alone = SceneHud.orders(walking = false, partner = false, others = 0, repeating = false, queued = 0) + assertEquals(listOf(HudOrder.WALK, HudOrder.PLAY, HudOrder.SAY, HudOrder.RELEASE, HudOrder.FREE_WILL), alone.map { it.order }) + val paired = SceneHud.orders(walking = true, partner = true, others = 2, repeating = false, queued = 0) + assertEquals(listOf(HudOrder.WALK, HudOrder.PLAY, HudOrder.PARTNER, HudOrder.SAY, HudOrder.CHAT, HudOrder.RELEASE), + SceneHud.page(paired, 0).map { it.order }) + assertTrue(paired.first().lit) + } + + @Test + fun noPageHoldsMoreThanSixAndPagesWrapBack() { + val all = SceneHud.orders(false, true, 3, repeating = true, queued = 2, + uses = listOf("CHAIR" to "Sit in chair", "COUCH" to "Sit on couch", "BED" to "Rest on bed", "TABLE" to "Read a book")) + assertEquals(13, all.size) + assertEquals(3, SceneHud.pages(all.size)) + for (p in 0 until 3) assertTrue(SceneHud.page(all, p).size <= SceneHud.SLOTS) + assertEquals(all, (0 until 3).flatMap { SceneHud.page(all, it) }) + assertEquals("Clear queue (2)", all.first { it.order == HudOrder.CLEAR_QUEUE }.label) + // a shorter bar under a later page: the last page there is + assertEquals(0, SceneHud.clampPage(2, 5)) + assertEquals(1, SceneHud.pages(0)) + // every slot's key differs (the object slots by their target) + assertEquals(all.size, all.map { it.key }.toSet().size) + } + + @Test + fun theFoldsScreensGetSixInARowOrTwoRowsOfThreeAndNothingWiderThanTheScreen() { + for ((w, h) in listOf(411f to 960f, 960f to 411f, 832f to 750f, 750f to 832f, 360f to 640f)) { + val l = SceneHud.layout(w, h) + assertTrue(l.barW <= w - 2 * SceneHud.MARGIN + 0.01f, "bar fits $w") + assertEquals(SceneHud.SLOTS, l.cols * l.rows) + assertTrue(l.slotW >= 88f, "slot wide enough to read at $w: ${l.slotW}") + assertEquals(l.rows * SceneHud.SLOT_H + (l.rows - 1) * SceneHud.GAP, l.barH) + } + assertEquals(3, SceneHud.layout(411f, 960f).cols) + assertFalse(SceneHud.layout(411f, 960f).castSide) + assertEquals(6, SceneHud.layout(960f, 411f).cols) + assertTrue(SceneHud.layout(832f, 750f).castSide) + } + + @Test + fun theHintSaysWhatATapDoesNow() { + assertEquals("Tap an NPC to direct them.", SceneHud.hint(false, false, 3, false)) + assertEquals("Tap another NPC to make them the partner.", SceneHud.hint(true, false, 2, false)) + assertEquals("Tap the floor to walk there.", SceneHud.hint(true, true, 2, true)) + assertEquals("", SceneHud.hint(true, false, 1, false)) + } + + @Test + fun theClockReadsAsTheGames() { + assertEquals("12:05 AM", SceneHud.clock(0, 5, false)) + assertEquals("9:30 PM", SceneHud.clock(21, 30, false)) + assertEquals("12:00 PM", SceneHud.clock(12, 0, false)) + assertEquals("07:04", SceneHud.clock(7, 4, true)) + } + + @Test + fun partnerTabComesFirstWithAPartnerAndOnlyWhenThereArePairs() { + val groups = listOf("Dances", "Partner", "Sitting", "Dances") + assertEquals(listOf("Partner", "All", "Dances", "Sitting"), SceneHud.animationTabs(groups, hasPairs = true, partnerFirst = true)) + assertEquals(listOf("All", "Dances", "Sitting", "Partner"), SceneHud.animationTabs(groups, hasPairs = true, partnerFirst = false)) + assertEquals(listOf("All", "Dances", "Sitting"), SceneHud.animationTabs(groups, hasPairs = false, partnerFirst = true)) + assertTrue(SceneHud.inTab("Partner", "Partner dances", 2)) + assertFalse(SceneHud.inTab("Partner", "Dances", 1)) + assertTrue(SceneHud.inTab("Dances", "Dances", 1)) + assertTrue(SceneHud.inTab("All", "x", 1)) + } +}