diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..9bdf2f6 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,39 @@ +## Pull Request Checklist + +- [ ] PR is targeting the `dev` branch +- [ ] I have pulled the latest changes from `dev` and resolved any merge conflicts +- [ ] My code follows the project’s style guidelines +- [ ] I have tested my changes and ensured they work as expected +- [ ] Relevant documentation/comments have been added or updated +- [ ] Any dependent changes have been merged + +### Resource Relevance and Usage +- [ ] Resource is active on 100+ servers, OR +- [ ] Resource has a verifiable dependency on community_bridge, OR +- [ ] Exception justified (adds value or supports project goals) + +### Avoiding Breaking Changes +- [ ] No breaking changes introduced, OR +- [ ] If deprecating: 2-4 month grace period provided +- [ ] Deprecation notices clearly documented in code with dates + +### Documentation and Testing +- [ ] At least one usage example included. +- [ ] IntelliSense-style comments added. +- [ ] Unit test coverage provided + +## Description + + + +## Related Issues + + + +## Testing Steps + + + +## Additional Notes + + \ No newline at end of file diff --git a/Attributions.md b/Attributions.md index 83c022d..454b883 100644 --- a/Attributions.md +++ b/Attributions.md @@ -1,37 +1,125 @@ -# Attributions +# 🙏 Attributions -This project incorporates code from several libraries and resources licensed under GPLv3, as it inherits their licensing, and the creators are credited below: +> **Community Bridge** stands on the shoulders of giants. This project incorporates code from several outstanding libraries and resources, all licensed under GPLv3. We're grateful to the talented developers who made their work available to the community. -## r_bridge -- **Purpose**: Code for codem-inventory bridging, targeting, and framework item registration. -- **Modifications to the code**: Code was used for codem/tgian inventory bridge & targeting, the idea of native helper functions came from that entirely. Targeting code has been altered to allow both formats, the item registration has been simplified to fit this use case. -- **Credit**: **r_bridge** inventory bridging code for codem-inventory is used in this. Targeting code still remains as is and is used. - [\[r_bridge\]](https://github.com/rumaier/r_bridge) +--- -## dirk_lib -- **Purpose**: Vehicle fuel, vehicle key bridging. -- **Modifications to the code**: None. -- **Credit**: **dirk_lib** client side code is used to manage vehicle fuel and keys, bridging these systems. - [\[dirk_lib\]](https://github.com/DirkDigglerz/dirk_lib) +## 📚 Libraries & Resources -## ox_lib -- **Purpose**: Utility functions for printing raycasting and point registering. -- **Credit**: **ox_lib** provides various utility functions for printing and interacting with other objects in this resource. While theres no code pulled directly from the resource, it is still the backbone to it so a thanks is nessesary. - [\[ox_lib\]](https://github.com/overextended/ox_lib) +### 🌉 r_bridge +**Purpose:** Code for codem-inventory bridging, targeting, and framework item registration +**Repository:** [r_bridge](https://github.com/rumaier/r_bridge) -## renewed_lib -- **Purpose**: Object placer functionality. -- **Modifications to the code**: Variable naming, added missing params for the natives used, updated a depreciated export from oxlib for the raycast camera, altered the showtext ui to now work with multiple showtextui systems, moved the text for placement into locales, the requestModel exports from ox_lib were replaced with the function my bridge uses to request models from ox_lib. -- **Credit**: **renewed_lib** code is used for its object placement snippet. - [\[renewed_lib\]](https://github.com/Renewed-Scripts/Renewed-Lib) +
+📝 Implementation Details +**Code we use:** +- Inventory bridging code for codem-inventory integration +- Targeting system foundation -## duff -- **Purpose**: Version Checker. -- **Modifications to the code**: Variables removed, now will pull repo information from passed string. -- **Credit**: **duff** code was refrenced and some used for version checker formatting and print style. - [\[duff\]](https://github.com/DonHulieo/duff/blob/d89ed3b0051194babf5711114a0c437d4e41f433/server/init.lua#L10C1-L28C4) +**Modifications made:** +- Adapted inventory bridge for codem compatibility in alternative structure +- Enhanced targeting code to support both QB and ox formats in alternative structure +
+--- -Thank you to the creators and maintainers of these libraries/bridges/internet points for their hard work and contributions to the FiveM community. +### 🔧 dirk_lib +**Purpose:** Vehicle fuel and vehicle key bridging systems +**Repository:** [dirk_lib](https://github.com/DirkDigglerz/dirk_lib) + +
+📝 Implementation Details + +**Code we use:** +- Client-side vehicle fuel management +- Vehicle key bridging functionality + +**Modifications made:** +- None - code used as-is with full credit to original author + +
+ +--- + +### 📦 ox_lib +**Purpose:** External compatibility and architectural inspiration +**Repository:** [ox_lib](https://github.com/overextended/ox_lib) + +
+📝 Implementation Details + +**Compatibility features:** +- External resource integration for raycasting utilities +- Shared architectural patterns and conventions + +**Implementation approach:** +- No direct code usage - maintains compatibility as external resource +- Follows ox_lib patterns and conventions for seamless integration +- Provides bridge compatibility for servers using ox_lib ecosystem + +
+ +--- + +### 🏗️ renewed_lib +**Purpose:** Object placer functionality +**Repository:** [renewed_lib](https://github.com/Renewed-Scripts/Renewed-Lib) + +
+📝 Implementation Details + +**Code we use:** +- Object placement system + +**Modifications made:** +- Updated variable naming for consistency +- Added missing parameters for native functions +- Updated deprecated ox_lib raycast camera export +- Enhanced showtext UI to work with multiple systems +- Moved placement text to locales for internationalization +- Replaced ox_lib model request exports with our bridge functions + +
+ +--- + +### 🔍 duff +**Purpose:** Version checker system and update notifications +**Repository:** [duff](https://github.com/DonHulieo/duff/blob/d89ed3b0051194babf5711114a0c437d4e41f433/server/init.lua#L10C1-L28C4) + +
+📝 Implementation Details + +**Code we use:** +- Version checker formatting patterns +- Update notification print styles +- Repository information handling + +**Modifications made:** +- Removed unnecessary variables +- Enhanced to pull repository information from passed strings +- Adapted print formatting for our use case + +
+ +--- + +## 🌟 Special Thanks + +A heartfelt thank you to all the creators and maintainers of these libraries, bridges, and resources. Your dedication to open-source development and the FiveM community makes projects like Community Bridge possible. + +Your willingness to share knowledge and code under GPLv3 licensing enables the entire community to build better, more compatible systems together. + +--- + +## 📜 License Compliance + +All incorporated code maintains its original GPLv3 licensing. Community Bridge inherits this license to ensure continued open-source availability and community collaboration. + +For detailed license information, see the [LICENSE](LICENSE) file in the project root. + +--- + +> *"If I have seen further it is by standing on the shoulders of Giants."* - Isaac Newton diff --git a/README.md b/README.md index 9f4e33d..7f71807 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,135 @@ -# 🌉 Community Bridge -**By The Order of the Sacred Framework** +# 🌉 Community Bridge +> **By The Order of the Sacred Framework** -Welcome to **Community Bridge**, a modular, beginner-friendly collection of tools and systems designed to simplify and unify development. Built with love and maintained by the community, this bridge aims to make scripting easier, cleaner, and more accessible for everyone. +
+ +![License](https://img.shields.io/badge/license-GPLv3-blue.svg) +![FiveM](https://img.shields.io/badge/FiveM-Compatible-green.svg) +![Version](https://img.shields.io/badge/version-latest-brightgreen.svg) +![Contributors](https://img.shields.io/github/contributors/The-Order-Of-The-Sacred-Framework/community_bridge?style=for-the-badge&logo=github&color=blue) + + +*A modular, beginner-friendly collection of tools and systems designed to simplify and unify FiveM development.* + +**Built with ❤️ by the community, for the community** + +
--- -## 🔧 Features +## 🚀 Overview & Features -This bridge includes a wide range of plug-and-play systems, built with maximum compatibility in mind: +**Community Bridge** is a comprehensive compatibility layer that acts as a universal wrapper around all major systems used across FiveM frameworks. Whether you're building with QB-Core, ESX, QBox, or any other framework, this bridge ensures your scripts work seamlessly across all environments. -- **Inventory Module** – Designed to work with `ox_inventory`, `codem-inventory`, `core_inventory`, `jpr-inventory`, `origin_inventory`, `ps-inventory`, `qb-inventory`, `qs-inventory`, and `tgiann-inventory`. Includes an **item output generator** supporting `ox_inventory`, `qb-new`, and `qb-old` formats. -- **Dispatch Module** – Compatible with `lb-tablet`, `ps-dispatch`, `qs-dispatch`, `redutzu-mdt`, `tk_dispatch`, `linden_outlawalert`, `cd_dispatch`, `bub_mdt`, and includes a built-in fallback to ensure notifications always get through. -- **Doorlock Module** – Supports `ox_doorlock`, `qb-doorlock`, `rcore_doorlock`, and `jacksams-doorlock`. -- **Framework Module** – Full support for `qb`, `qbox`, and `esx` with built-in fallbacks for maximum compatibility. -- **Fuel System Module** – Works seamlessly with all major fuel systems. -- **HelpText & Notify Modules** – Designed to support all popular systems with framework-level fallbacks. -- **Input Module** – Compatible with both `qb-input` and `ox_lib` input methods. -- **Management Module** – Works with most major management system variants. -- **Menu Module** – Accepts both `qb` and `ox_lib` formats interchangeably. -- **Phone Module** – Compatible with all major phone systems. -- **Progress Bar Module** – Supports most commonly used progress bar resources. -- **Shops Module** – An in-house shops system, simple to use and easy to expand. -- **Skills Module** – Supports most skills systems in the ecosystem. -- **Targeting Module** – Built to work with `qb-target`, `ox_target`, and `sleepless-interact`. -- **Vehicle Key Module** – Compatible with all major vehicle key systems. -- **Version Checker Module** – Built to handle version checks for both free and paid scripts across any setup. -- **Weather Module** – Fully compatible with most weather control resources. +Instead of writing separate code for each framework's inventory, dispatch, targeting, or notification system, you write once and it works everywhere. -Also includes: -- Locale support -- Math utilities -- A rich collection of helper functions -- And more... +### 🎯 Core Philosophy +- 🔧 **Plug & Play** - Drop in and it just works +- 🌐 **Universal Compatibility** - One bridge, all frameworks +- 📚 **Beginner Friendly** - Clean, documented, and easy to understand +- 🚀 **Future Proof** - Built to adapt and grow with the community + +### 🔐 **Framework Support** +- **QB-Core** - Full compatibility +- **QBox** - Native support +- **ESX** - Complete integration +- **Custom Frameworks** - Extensible design + +Below are the core system integrations and advanced tools available: + +### 🔧 **Core System Integrations** +
+Click to expand core system compatibility + +#### 📦 **Inventory Systems** +- `ox_inventory` ⭐ | `codem-inventory` | `core_inventory` | `jpr-inventory` +- `origin_inventory` | `ps-inventory` | `qb-inventory` | `qs-inventory` | `tgiann-inventory` + +**Bonus:** Built-in item output generator supporting `ox_inventory`, `qb-new`, and `qb-old` formats! + +#### 🚨 **Dispatch Systems** +- `lb-tablet` | `ps-dispatch` | `qs-dispatch` | `redutzu-mdt` | `tk_dispatch` +- `linden_outlawalert` | `cd_dispatch` | `bub_mdt` + +**Plus:** Built-in fallback system ensures notifications always reach their destination. + +#### 🏗️ **Additional Modules** +| Module | Description | Compatibility | +|--------|-------------|---------------| +| 🚪 **Doorlock** | Universal door management | `ox_doorlock`, `qb-doorlock`, `rcore_doorlock`, `jacksams-doorlock` | +| ⛽ **Fuel Systems** | Seamless fuel integration | All major fuel resources | +| 📱 **Phone** | Cross-phone compatibility | All major phone systems | +| 🎯 **Targeting** | Universal targeting system | `qb-target`, `ox_target`, `sleepless-interact` | +| 🔑 **Vehicle Keys** | Key management bridge | All major key systems | +| 🛍️ **Shops** | In-house shop system | Simple, expandable design | +| 📊 **Progress Bars** | Universal progress system | Most common progress resources | +| 🌤️ **Weather** | Weather control bridge | Most weather resources | +| 🎮 **Skills** | Skill system integration | Most skill systems | + +
+ +### 🎨 **Developer Tools & Utilities** +
+Click to expand developer tools and utilities + +#### 🛠️ **Utility Features** +- 🌍 **Locale Support** - Multi-language ready +- 🧮 **Math Utilities** - Common mathematical functions +- 🔧 **Helper Functions** - Rich collection of development tools +- 📏 **Input Systems** - `qb-input` and `ox_lib` compatible +- 📋 **Menu Systems** - Interchangeable QB and ox_lib formats +- ✅ **Version Checker** - Built-in update management +- 📦 **Cache System** - Advanced client-side caching with change detection +- 🎯 **Point System** - 3D world interaction points +- 📊 **State Bags** - Entity state management +- 🔧 **Entity Management** - Comprehensive entity utilities + +#### 🎨 **Advanced Developer Tools** +- 🎬 **Cutscenes** - Full cinematic sequence management with character switching +- ✨ **Particle Effects** - Advanced particle system integration +- 📍 **Markers** - Server-side marker management system +- 🎯 **Raycast Utilities** - Advanced raycasting and collision detection +- 📺 **Scaleform** - Native UI scaleform wrapper +- 🎮 **Gizmo System** - 3D object manipulation with translate/rotate/scale +- 🏗️ **Object Placement** - Advanced placeable object system with boundary checks +- 🖥️ **DUI System** - Direct User Interface integration +- 📐 **Math Tools** - Mathematical utilities for 3D calculations + +
+ +### 🎭 **Specialized Systems** +
+Click to expand specialized system integrations + +#### 🏠 **Housing System Integration** +- 🏡 **bcs-housing** - Complete integration +- 🏠 **esx_property** - Full compatibility +- 🔧 **Universal Interface** - Standardized housing functions +- 📊 **Property Management** - Advanced property utilities + +#### 💬 **Dialogue & Help Systems** +- 🗣️ **Web-based Dialogue** - Modern React-based dialogue interface +- 💡 **Multiple Help Text Providers**: + - `cd_drawtextui` | `jg-textui` | `lab-HintUI` | `okokTextUI` | `ox_lib` +- 🎨 **Styled Components** - Professional UI with animations +- 📱 **Responsive Design** - Works across all screen sizes + +#### 👕 **Comprehensive Clothing Systems** +- 👔 **illenium-appearance** - Advanced appearance management +- 🎮 **fivem-appearance** - Community appearance system +- 📦 **qb-clothing** - QB-Core clothing integration +- 👗 **esx_skin** - ESX skin system support +- 🔄 **Default Fallback** - Built-in clothing system +- 💾 **Appearance Caching** - Optimized appearance data management + +#### 🎭 **Animation & Effects Systems** +- 🎬 **Animation Library** - Comprehensive animation utilities +- ✨ **Particle Management** - Advanced particle effect system +- 🎭 **Cutscene Framework** - Full cinematic control +- 📺 **Scaleform Integration** - Native UI elements +- 🎯 **Entity Animation** - Ped and object animation tools + +
Whether you're building a full framework or just need utility features, **Community Bridge** is designed to make your workflow easier and more efficient. @@ -47,12 +145,42 @@ Our mission: to promote open collaboration, reduce friction between systems, and ## 🧰 Why Use Community Bridge? -- ✅ Easy for beginners -- 🔄 Highly modular and extendable -- 🔌 Compatible with all major scripts and systems -- 🔧 Built-in compatibility wrappers -- 📦 Future-proof and easy to expand -- 🤝 Built with community-first values +- ✅ **Easy for beginners** - Simple, intuitive API design +- 🔄 **Highly modular** - Use only what you need +- 🔌 **Universal compatibility** - Works with all major frameworks and resources +- 🤝 **Community-driven** - Built by developers, for developers +- 🛡️ **Production ready** - Battle-tested across hundreds of servers + +--- + +## ❓ Frequently Asked Questions + +
+Click to expand FAQ + +**Q: What happens if a new framework comes out?** +A: We actively monitor the FiveM community and add support for new frameworks as they gain adoption. + +**Q: Is this compatible with my custom framework?** +A: Yes! Community Bridge has an extensible design that supports custom framework integration. + +**Q: How often is this updated?** +A: We release updates regularly to maintain compatibility and add new features based on community feedback. + +
+ +--- + +## 🚀 Quick Start + +### Installation +1. **Download** the latest release from GitHub +2. **Extract** to your resources folder: `[bridges]/community_bridge` +3. **Add** to your `server.cfg`: + ```cfg + ensure community_bridge + ``` +4. **Restart** your server --- @@ -63,6 +191,24 @@ Read the full documentation here: --- +## 🤝 Contributing + +We welcome contributions from the community! Here's how you can help: + +### How to Contribute +1. **Fork** this repositorys dev branch +2. **Commit** your changes (`git commit -m 'Add amazing feature'`) +3. **Push** to the branch (`git push origin feature/amazing-feature`) +4. **Open** a Pull Request + +### Guidelines +- ✅ Follow existing code style and patterns +- ✅ Test your changes thoroughly +- ✅ Update documentation when needed +- ✅ Be respectful and constructive in discussions + +--- + ## 💬 Join the Community Have questions, suggestions, or want to contribute? Join us on Discord: @@ -70,6 +216,143 @@ Have questions, suggestions, or want to contribute? Join us on Discord: --- -> “A bridge built not for one, but for all — strong, simple, and open.” +## 📄 License + +This project is licensed under the **GPLv3 License** - see the [LICENSE](LICENSE) file for details. + +### Attribution +Some modules include contributions from the FiveM community. Full attributions are listed in the `Attributions` file. --- + +## ⭐ Support the Project + +If Community Bridge has helped your development workflow, consider: +- ⭐ **Starring** this repository +- 🐛 **Reporting** bugs and issues +- 💡 **Suggesting** new features +- 🤝 **Contributing** code or documentation +- 💬 **Sharing** with other developers + +--- + +> "Connecting what matters — frameworks unified, development simplified." + +
+ +**Made with ❤️ by The Order of the Sacred Framework** + +![GitHub stars](https://img.shields.io/github/stars/The-Order-Of-The-Sacred-Framework/community_bridge?style=social) +![Discord](https://img.shields.io/discord/1337224918710095882?style=social) + +
+ +--- + +## 🔍 SEO & Keywords + +
+Click to expand SEO information and keywords + +### 🏷️ Primary Keywords +- **FiveM Bridge** - Universal compatibility layer for FiveM servers +- **FiveM Framework Compatibility** - Cross-framework development solution +- **QB-Core Bridge** - QB-Core to universal system bridge +- **ESX Bridge** - ESX framework compatibility layer +- **QBox Framework Support** - QBox integration and compatibility +- **FiveM Development Tools** - Comprehensive development utilities +- **FiveM Resource Bridge** - Universal resource compatibility system +- **Lua FiveM Framework** - Lua-based framework unification + +### 🎯 Secondary Keywords +- FiveM inventory bridge, FiveM dispatch integration, FiveM targeting system +- Universal FiveM scripts, Cross-framework FiveM resources, FiveM compatibility layer +- QB-Core ESX bridge, Multi-framework FiveM development, FiveM script compatibility +- Open source FiveM bridge, Community FiveM tools, FiveM developer resources +- Modular FiveM framework, Beginner-friendly FiveM development, FiveM code bridge + +### 🌐 Long-tail Keywords +- "How to make FiveM scripts work with multiple frameworks" +- "Universal FiveM framework compatibility solution" +- "FiveM QB-Core ESX QBox bridge resource" +- "Cross-framework FiveM development made easy" +- "One script multiple FiveM frameworks compatibility" +- "FiveM framework agnostic development tools" +- "community_bridge" +- "communitybridge" +- "community-bridge" +- "Universal FiveM inventory dispatch targeting bridge" + +### 📊 Technical Tags +`fivem` `lua` `qb-core` `esx` `qbox` `framework` `bridge` `compatibility` `universal` `modular` `open-source` `community` `development` `tools` `utilities` `scripts` `resources` `gta5` `roleplay` `server` `multiplayer` `fivem-scripts` `fxmanifest` `citizenfx` `rockstar-games` `gtav` `gta-online` `server-sided` `client-sided` `shared-resources` `ox-lib` `ox-inventory` `qb-inventory` `ps-inventory` `vrp` `standalone` `mysql` `oxmysql` `nui` `ui` `html` `css` `javascript` `typescript` `json` `cfg` `config` `exports` `events` `callbacks` `threading` `optimization` + +### 🎮 Gaming & RP Tags +`gta5-mods` `roleplay-server` `fivem-server` `gta-roleplay` `multiplayer-gaming` `server-development` `game-modifications` `roleplay-framework` `gaming-community` `server-resources` `rp-server` `roleplay-scripts` `fivem-mods` `gta-mods` `custom-scripts` `server-scripts` `roleplay-resources` `fivem-resources` `gtarp` `rp-framework` `city-roleplay` `serious-rp` `whitelist-server` `public-server` `economy-scripts` `job-scripts` `gang-scripts` `police-scripts` `ems-scripts` `mechanic-scripts` `real-estate` `housing-system` `vehicle-system` `inventory-system` `banking-system` `phone-system` `dispatch-system` `mdt-system` `clothing-system` `appearance-system` + +### 🔧 Developer Tags +`lua-scripting` `game-development` `framework-integration` `api-wrapper` `developer-tools` `code-bridge` `system-integration` `modular-design` `plug-and-play` `cross-platform` `fivem-development` `cfx-server` `server-owner` `server-admin` `fivem-coding` `lua-programming` `gta-scripting` `mod-development` `resource-development` `script-development` `fivem-framework` `qb-development` `esx-development` `custom-framework` `framework-bridge` `universal-bridge` `compatibility-layer` `multi-framework` `cross-framework` `framework-agnostic` `developer-friendly` `beginner-friendly` `advanced-scripting` `professional-scripts` `production-ready` `server-optimization` `performance-optimization` `code-optimization` + +### 🚀 Popular FiveM Community Tags +`fivem-community` `cfx-community` `roleplay-community` `gta-community` `mod-community` `script-sharing` `open-source-fivem` `fivem-github` `fivem-discord` `fivem-forum` `tebex-fivem` `fivem-store` `premium-scripts` `free-scripts` `leaked-scripts` `custom-vehicles` `custom-maps` `custom-sounds` `custom-weapons` `custom-clothing` `mlo` `ymap` `stream-files` `replace-files` `addon-vehicles` `replace-vehicles` `car-pack` `weapon-pack` `clothing-pack` `sound-pack` + +### 🏢 Business & Economy Tags +`fivem-business` `roleplay-economy` `virtual-economy` `in-game-currency` `money-system` `shop-system` `marketplace` `auction-system` `real-estate-system` `property-system` `rental-system` `loan-system` `tax-system` `paycheck-system` `salary-system` `job-payment` `commission-system` `trading-system` `crafting-system` `manufacturing` `farming-system` `mining-system` `fishing-system` + +### 🚔 Emergency Services Tags +`police-system` `sheriff-department` `state-police` `federal-agents` `ems-system` `fire-department` `ambulance-service` `dispatch-center` `911-system` `emergency-response` `law-enforcement` `first-responders` `medical-system` `hospital-system` `jail-system` `prison-system` `court-system` `legal-system` `lawyer-system` `judge-system` `probation-system` + +### 🏎️ Vehicle & Transportation Tags +`vehicle-system` `car-dealership` `vehicle-shop` `custom-vehicles` `vehicle-modifications` `vehicle-tuning` `racing-system` `drag-racing` `street-racing` `car-meets` `vehicle-rental` `taxi-system` `uber-system` `trucking-system` `delivery-system` `towing-system` `impound-system` `vehicle-insurance` `fuel-system` `garage-system` `parking-system` `traffic-system` `speed-cameras` `toll-system` + +### 🎭 Character & Appearance Tags +`character-creation` `character-customization` `appearance-system` `clothing-system` `barber-system` `tattoo-system` `makeup-system` `accessories` `jewelry-system` `character-stats` `skill-system` `leveling-system` `experience-system` `reputation-system` `gang-system` `faction-system` `organization-system` `whitelist-system` `character-slots` `character-selection` + +### 🏠 Housing & Properties Tags +`housing-system` `real-estate` `property-system` `apartment-system` `house-system` `mansion-system` `interior-system` `furniture-system` `decoration-system` `roommate-system` `landlord-system` `rent-system` `mortgage-system` `property-management` `neighborhood-system` `gated-community` `luxury-homes` `affordable-housing` + +### 📦 Inventory System Tags +`ox-inventory` `qb-inventory` `ps-inventory` `qs-inventory` `codem-inventory` `core-inventory` `jpr-inventory` `tgiann-inventory` `origen-inventory` `inventory-bridge` `universal-inventory` `inventory-system` `item-system` `crafting-inventory` `weight-system` `slot-system` `inventory-ui` `item-metadata` `inventory-exports` + +### 🚨 Dispatch & MDT System Tags +`ps-dispatch` `cd-dispatch` `qs-dispatch` `lb-tablet` `bub-mdt` `redutzu-mdt` `tk-dispatch` `linden-outlawalert` `dispatch-system` `mdt-system` `911-dispatch` `emergency-dispatch` `police-dispatch` `ems-dispatch` `fire-dispatch` `dispatch-bridge` `universal-dispatch` `alert-system` + +### 🎯 Target System Tags +`ox-target` `qb-target` `sleepless-interact` `target-system` `interaction-system` `targeting-bridge` `universal-targeting` `entity-targeting` `object-interaction` `ped-interaction` `vehicle-interaction` `zone-targeting` `raycast-targeting` `contextual-interaction` + +### 🚪 Doorlock System Tags +`ox-doorlock` `qb-doorlock` `rcore-doorlock` `doors-creator` `doorlock-system` `door-bridge` `universal-doorlock` `access-control` `key-system` `lock-system` `security-system` `door-management` `restricted-access` `keycard-system` + +### 🔑 Vehicle Key System Tags +`qb-vehiclekeys` `qbx-vehiclekeys` `cd-garage` `okokgarage` `jacksam` `wasabi-carlock` `qs-vehiclekeys` `renewed-vehiclekeys` `t1ger-keys` `mk-vehiclekeys` `mono-carkeys` `mrnewbvehiclekeys` `f-realcarkeyssystem` `vehicle-keys` `car-keys` `key-system` `vehicle-security` `keyless-entry` `immobilizer` `hotwire-system` + +### ⛽ Fuel System Tags +`ox-fuel` `ps-fuel` `qs-fuelstations` `legacyfuel` `cdn-fuel` `renewed-fuel` `ti-fuel` `x-fuel` `lc-fuel` `bigdaddy-fuel` `esx-sna-fuel` `okokgasstation` `fuel-system` `gas-station` `vehicle-fuel` `fuel-consumption` `refueling` `fuel-economy` `electric-vehicles` + +### 🏠 Housing Integration Tags +`qb-houses` `qb-appartments` `ps-housing` `bcs-housing` `esx-property` `housing-bridge` `property-bridge` `real-estate-bridge` `apartment-system` `house-system` `interior-system` `property-management` `housing-compatibility` + +### 📱 Phone System Tags +`lb-phone` `okokphone` `qs-smartphone` `gksphone` `phone-system` `smartphone` `mobile-phone` `phone-bridge` `universal-phone` `communication-system` `messaging-system` `call-system` `contact-system` `phone-apps` + +### 🔔 Notification System Tags +`ox-lib` `okoknotify` `mythic-notify` `t-notify` `r-notify` `pnotify` `wasabi-notify` `notification-system` `alert-system` `notify-bridge` `universal-notifications` `toast-notifications` `popup-system` `message-system` + +### 💰 Banking System Tags +`qb-banking` `renewed-banking` `fd-banking` `okokbanking` `banking-system` `financial-system` `atm-system` `bank-account` `transaction-system` `money-transfer` `payment-system` `banking-bridge` `universal-banking` + +### 👕 Clothing & Appearance Tags +`qb-clothing` `fivem-appearance` `illenium-appearance` `esx-skin` `clothing-system` `appearance-system` `character-customization` `wardrobe-system` `outfit-system` `skin-system` `customization-bridge` `appearance-bridge` + +### 🌤️ Weather System Tags +`qb-weathersync` `renewed-weathersync` `cd-easytime` `weather-system` `time-system` `weather-sync` `climate-system` `day-night-cycle` `weather-bridge` `environmental-system` + +### 📈 Skills & XP System Tags +`pickle-xp` `ot-skills` `evolent-skills` `skill-system` `experience-system` `leveling-system` `progression-system` `xp-system` `character-stats` `skills-bridge` `universal-skills` + +### 💬 UI & Input System Tags +`ox-lib` `qb-input` `qb-menu` `qb-progressbar` `cd-drawtextui` `jg-textui` `lab-hintui` `okoktextui` `ui-system` `input-system` `menu-system` `progressbar-system` `textui-system` `help-system` `user-interface` `interactive-ui` + +### 🏗️ Framework Integration Tags +`qb-core` `qbx-core` `es-extended` `esx` `qbox` `framework-bridge` `multi-framework` `cross-framework` `framework-compatibility` `universal-framework` `framework-agnostic` `compatibility-layer` `bridge-system` `framework-unification` + +
diff --git a/components/Class.lua b/components/Class.lua deleted file mode 100644 index bf89cb7..0000000 --- a/components/Class.lua +++ /dev/null @@ -1,154 +0,0 @@ - -local Tables = Require('use/tables.lua') -local Ids = Require("use/ids.lua") - -local AllInstances = {} - - ----@class Class -Class = {} -Class.ClassName = "Class" -Class.__call = function(this, ...) - return this:new(...) -end -Builders = {} - -function Class.SetInstance(instance) - AllInstances[instance.id] = instance -end - -function Class.GetInstance(id) - return AllInstances[id] -end - ---- Default (empty) constructor ---- @param self Class ---- @vararg any -function Class:init(...) end - ---- Creates a subclass of the current class. ---- This function copies the properties and methods of the current class to a new object. ---- It also sets up metatables to allow for object-oriented behavior, such as method calls and property access. ---- @param obj object | nil: The table to extend. If nil, a new table will be created. ---- @return obj object: The extended object with properties and methods from the given class obj. -function Class:extend(obj) - local className = obj.ClassName or "Class" - - - local old = Tables.DeepClone(self, {}, {components = true}) - local new = Tables.DeepClone(obj, old, {ClassName = true}) - - new.components = self.components or {} - new.components[className] = obj - - if not new.id then new.id = Ids.CreateUniqueId(new.components) end - - -- create new objects directly, like o = Object() - self = setmetatable(new, Class) - - if not Class.GetInstance(new.id) then Class.SetInstance(self) end - return self -end - ---- Sets a property on the object. NOTE: This is mostly for internal purposes. ---- @param prop string|table: The property name or a table of properties to set. ---- @param value any: The value to set the property to. -function Class:set(prop, value) - if not value and type(prop) == "table" then - for k, v in pairs(prop) do - rawset(self._, k, v) - end - else - rawset(self._, prop, value) - end -end - ---- This function is used to create a new instance of the class. ---- It calls the init function if it exists. ---- @vararg any: The arguments to pass to the init ---- @return object: The new instance of the class. -function Class:new(...) - local obj = self:extend({}) - if obj.init then obj:init(...) end - return obj -end - ---- This function is used to create a new instance of the class. ---- It calls the struct function if it exists. ---- @vararg object(s): List of objects to extend the class with. ---- @return object: The new instance of the class with the data and functions from the objects passed. -function class(className, ...) - local newObj = Class:extend({}) - local components = table.pack(...) - newObj.ClassName = className - if components then - for k, v in pairs(components) do - local clName = v.ClassName - if not Builders[clName] then -- builders are used to reconstruct an object usually when pulled from server to client or vice versa - Builders[clName] = Tables.DeepClone(newObj) - end - end - end - if components.n > 0 then - for k, v in pairs(components) do - if k ~= "n" then - local newNewObject = nil - if v.Struct and type(v.Struct) == "function" then - newNewObject = v:Struct() - end - newObj = newObj:extend(newNewObject or v) - end - end - else - return newObj - end - - return newObj -end - -function reconstruct(obj) - local newTable = {} - local tbl = obj.components or {} - for k, v in pairs(tbl) do - local builder = Builders[k] - if builder then - newTable[k] = builder - end - end - return class(table.unpack(newTable)) -end - ---- Overwrites the type(self) value to return "Class". ---- @return string: The string "Class". -function Class:__type() - return self.ClassName or "Class" -end - ---- Overwrites the call operator to call the new function. Ex: Class() ---- @vararg any: The arguments to pass to the new function. ---- @return object: The new instance of the class. -function Class:__call(...) - return self:new(...) -end - - ---- Checks to see if the class is an instance of the given class. ---- @param cls Class: The class to check against. ---- @return boolean: True if the class is an instance of the given class, false otherwise. -function Class:IsA(cls) - local p = promise.new() - CreateThread(function() - local m = getmetatable(self) - while m do - if m == cls then - return p:resolve(true) - end - m = getmetatable(m) - Wait(0) - end - return p:resolve(false) - end) - return Citizen.Await(p) -end - -return {Class, class} \ No newline at end of file diff --git a/components/Singleton.lua b/components/Singleton.lua deleted file mode 100644 index 168e0c3..0000000 --- a/components/Singleton.lua +++ /dev/null @@ -1,38 +0,0 @@ -local classModule = Require("components/class.lua") -local _, class = table.unpack(classModule) - --- Registry to store singletons for classes -local SingletonRegistry = {} - ---- @class Singleton -local Singleton = class() -Singleton.ClassName = "Singleton" ---- Ensures the class instance is a singleton. ---- If an instance already exists, it returns the existing one. ---- If not, it initializes and registers a new singleton. -function Singleton:Struct() - local className = self.ClassName or "UnnamedClass" - -- Check if the singleton already exists - if SingletonRegistry[className] then - self = SingletonRegistry[className] - return self - end - -- Register this instance as the singleton for its class - SingletonRegistry[className] = self - return self -end ---- Clears the singleton instance for this class (if needed). -function Singleton:ClearSingleton() - local destroy = self.Destroy - if destroy and type(destroy) == "function" then self:Destroy() end - local className = self.ClassName or "UnnamedClass" - SingletonRegistry[className] = nil -end ---- Returns the existing singleton for a class. ---- @param className string: The name of the class to check. ---- @return any: The singleton instance, or nil if none exists. -function Singleton.Get(className) - return SingletonRegistry[className] -end - -return Singleton \ No newline at end of file diff --git a/components/Sync.lua b/components/Sync.lua deleted file mode 100644 index d09426a..0000000 --- a/components/Sync.lua +++ /dev/null @@ -1,103 +0,0 @@ -local classModule = Require("components/class.lua") -local _, class = table.unpack(classModule) -local ids = Require("use/ids.lua") - -local SyncObjects = {} - -function GetSyncObject(syndId) - return SyncObjects[syndId] -end - -function GetSyncObjects() - return SyncObjects -end - -function SetSyncObject(syncId, sync) - SyncObjects[syncId] = sync -end - ---- @class Sync -local Sync = class("Sync") ---- Initializes the Sync object. -function Sync:Struct() - self.syncId = ids.CreateUniqueId(SyncObjects) - self.sync = {} - self.updateWaitTime = 500 - SyncObjects[self.syncId] = self - return self -end - ---- Retrieves the value associated with the given key in the sync table. ---- @param key any: The key to retrieve the value for. ---- @return any: The value associated with the key. -function Sync:GetSyncKey(key) - return self.sync[key] -end - ---- Called when a sync key is initialized. ---- @param key any: The key being initialized. ---- @param value any: The value being set. -function Sync:OnSyncKeyInit(key, value) end - ---- Called when a sync key is updated. ---- @param key any: The key being updated. ---- @param oldValue any: The old value of the key. ---- @param newValue any: The new value of the key. -function Sync:OnSyncKeyUpdate(key, oldValue, newValue) end - ---- Called when a sync key is removed. ---- @param key any: The key being removed. -function Sync:OnSyncKeyRemove(key) end - --- Server -if not IsDuplicityVersion() then goto client end - ---- Sets a sync key and triggers a client event to update the sync table. ---- @param key any: The key to set. ---- @param value any: The value to set for the key. -function Sync:SetSynckey(key, value) - self.sync[key] = value - CreateThread(function() - SetTimeout(self.updateWaitTime, function() - TriggerClientEvent("Sync:Setup", -1, self.syncId, self.sync) - end) - end) -end - --- Client -if IsDuplicityVersion() then return Sync end -::client:: - ---- Compares the current sync table with a new table and updates accordingly. ---- @param newTable table: The new sync table to compare with. -function Sync:_CompareAndUpdate(newTable) - local oldTable = self.sync - for key, oldValue in pairs(oldTable) do - local newValue = newTable[key] - if newValue == nil then - self:OnSyncKeyRemove(key) - elseif oldValue ~= newValue then - self:OnSyncKeyUpdate(key, oldValue, newValue) - end - end - - for key, newValue in pairs(newTable) do - if oldTable[key] == nil then - self:OnSyncKeyInit(key, newValue) - end - end - self.sync = newTable -end - -RegisterNetEvent("Sync:Setup", function(syncId, sync) - local syncObj = GetSyncObject(syncId) - if not syncObj then - syncObj = reconstruct(Sync) - assert(syncObj, "Failed to sync: ", syncId) - syncObj.syncId = syncId - SetSyncObject(syncId, syncObj) - end - syncObj:_CompareAndUpdate(sync) -end) - -return table.pack({Sync}) diff --git a/fxmanifest.lua b/fxmanifest.lua index 85fe010..b0663da 100644 --- a/fxmanifest.lua +++ b/fxmanifest.lua @@ -5,7 +5,7 @@ use_experimental_fxv2_oal 'yes' author 'The Order of the Sacred Framework' name 'community_bridge' description 'A Universal Bridge for Our Community, created by a group of contributors with a shared vision to enhance both user and developer experiences. This bridge connects various frameworks, inventories, target systems, notification systems, and more, fostering compatibility and seamless integration.' -version '0.8.1' +version '0.9.0' shared_scripts { '@ox_lib/init.lua', @@ -13,6 +13,7 @@ shared_scripts { 'lib/init.lua', 'modules/math/*.lua', 'modules/locales/*.lua', + 'modules/clothing/**/shared.lua', } server_scripts { @@ -50,16 +51,16 @@ client_scripts { 'modules/dispatch/**/client.lua', 'modules/progressbar/**/client.lua', 'modules/clothing/**/client.lua', - 'modules/input/*.lua', + 'modules/input/**/client.lua', 'modules/menu/*.lua', 'modules/helptext/**/client.lua', 'modules/notify/**/client.lua', 'modules/dialogue/**/client/*.lua', 'modules/shops/**/client.lua', 'modules/housing/**/client.lua', - 'modules/accessibility/client.lua', 'modules/skills/**/client.lua', 'init.lua', + -- 'unit_tests/input_test.lua', } ui_page 'web/dist/index.html' @@ -72,6 +73,7 @@ files { 'lib/**/client/*.lua', 'lib/**/shared/*.lua', 'lib/**/server/*.lua', + 'modules/**', 'settings/*.lua', 'lib/init.lua', } diff --git a/init.lua b/init.lua index 2fc7e21..c8fbbcc 100644 --- a/init.lua +++ b/init.lua @@ -10,7 +10,7 @@ function Bridge.RegisterModule(moduleName, moduleTable) local wrappedModule = Bridge[moduleName] or {} if type(moduleTable) == 'function' then - Bridge[moduleName] = wrappedModule + Bridge[moduleName] = moduleTable exports(moduleName, moduleTable) return end @@ -104,5 +104,4 @@ Bridge.RegisterModule("Weather", Weather) Bridge.RegisterModule("Target", Target) Bridge.RegisterModule("Menu", Menu) -Bridge.RegisterModule("Dialogue", Dialogue) -Bridge.RegisterModule("Accessibility", Accessibility) -- new \ No newline at end of file +Bridge.RegisterModule("Dialogue", Dialogue) \ No newline at end of file diff --git a/lib/anim/client/client.lua b/lib/anim/client/client.lua index b809317..be46004 100644 --- a/lib/anim/client/client.lua +++ b/lib/anim/client/client.lua @@ -25,7 +25,6 @@ function Anim.RequestDict(animDict) end --- This will start the animation update loop. ---- @return void function Anim.Start() if Anim.isUpdateLoopRunning then return end Anim.isUpdateLoopRunning = true @@ -37,15 +36,13 @@ function Anim.Start() end if #idsToProcess == 0 then - Wait(750) + Wait(750) else for _, id in ipairs(idsToProcess) do - local animData = Anim.Active[id] - - if animData then + local animData = Anim.Active[id] + if animData then local entity = animData.entity - local onComplete = animData.onComplete - + local onComplete = animData.onComplete if not DoesEntityExist(entity) then if onComplete then onComplete(false, "despawned") end Anim.Active[id] = nil @@ -54,10 +51,8 @@ function Anim.Start() animData.startTime = GetGameTimer() animData.animEndTime = animData.duration > 0 and (animData.startTime + animData.duration) or -1 animData.status = "playing" - elseif animData.status == "playing" then local animationCompletedNaturally = false - if animData.duration == -1 then if not IsEntityPlayingAnim(entity, animData.animDict, animData.animName, 3) and GetEntityAnimCurrentTime(entity, animData.animDict, animData.animName) > 0.8 then animationCompletedNaturally = true @@ -65,17 +60,16 @@ function Anim.Start() elseif animData.animEndTime ~= -1 and GetGameTimer() >= animData.animEndTime then animationCompletedNaturally = true end - if animationCompletedNaturally then if onComplete then onComplete(true, "completed") end Anim.Active[id] = nil end end - end - end - Wait(100) - end - end + end + end + Wait(100) + end + end end) end @@ -92,7 +86,7 @@ end --- @param onComplete function | nil --- @return string | nil function Anim.Play(id, entity, animDict, animName, blendIn, blendOut, duration, flag, playbackRate, onComplete) - local newId = id or Ids.CreateUniqueId(Anim.Active) + local newId = id or Ids.CreateUniqueId(Anim.Active) if Anim.Active[newId] then if onComplete then onComplete(false, "id_in_use") @@ -111,7 +105,7 @@ function Anim.Play(id, entity, animDict, animName, blendIn, blendOut, duration, if onComplete then onComplete(false, "dict_load_failed") end - return nil + return nil end Anim.Active[newId] = { @@ -124,7 +118,7 @@ function Anim.Play(id, entity, animDict, animName, blendIn, blendOut, duration, flag = flag or 1, playbackRate = playbackRate or 0.0, onComplete = onComplete, - status = "pending_task", + status = "pending_task", startTime = 0, animEndTime = 0 } @@ -139,7 +133,7 @@ function Anim.Stop(id) end local animData = Anim.Active[id] - + if animData.entity and DoesEntityExist(animData.entity) and IsEntityAPed(animData.entity) then if animData.status == "playing" or animData.status == "pending_task" then StopAnimTask(animData.entity, animData.animDict, animData.animName, 1.0) @@ -150,7 +144,7 @@ function Anim.Stop(id) animData.onComplete(false, "stopped_by_id") end - Anim.Active[id] = nil + Anim.Active[id] = nil local anyLeft = Anim.Active and next(Anim.Active) ~= nil if not anyLeft then Anim.isUpdateLoopRunning = false diff --git a/lib/cache/shared/cache.lua b/lib/cache/shared/cache.lua index cf42a32..dfd76d1 100644 --- a/lib/cache/shared/cache.lua +++ b/lib/cache/shared/cache.lua @@ -13,7 +13,10 @@ ---@field Get fun(name:string): any ---@field OnChange fun(name:string, onChange:fun(new:any, old:any)) ---@field Remove fun(name:string) -local Cache = {} ---@type CacheModule +Cache = Cache or {} ---@type CacheModule -- <-- we use Cache as a global variable so that if we dont required it more than once + +Table = Table or Require('lib/utility/shared/tables.lua') +Id = Id or Require('lib/utility/shared/ids.lua') local Config = Require("settings/sharedConfig.lua") local max = 5000 @@ -22,6 +25,11 @@ local Wait = Wait local GetGameTimer = GetGameTimer local resourceCallbacks = {} -- Add callbacks from resources +local resourceTracker = { + caches = {}, + callbacks = {}, + initialized = {} +} Cache.Caches = Cache.Caches or {} Cache.LoopRunning = Cache.LoopRunning or false @@ -49,13 +57,10 @@ local function processCacheEntry(now, cache) if remaining <= 0 then local oldValue = cache.Value - cache.Value = cache.Compare() - if cache.Value ~= oldValue and cache.OnChange then - for i, onChange in ipairs(cache.OnChange) do - Citizen.CreateThreadNow(function() - Wait(0) - onChange(cache.Value, oldValue) - end) + cache.Value = cache.Compare() + if not Table.Compare(cache.Value, oldValue) and cache.OnChange then + for i, onChange in pairs(cache.OnChange) do + onChange(cache.Value, oldValue) end end cache.LastChecked = now @@ -99,6 +104,53 @@ local function StartLoop() end) end +local function trackResource(resourceName, type, data) + if not resourceName then return end + + -- Initialize resource tracking if needed + if not resourceTracker.initialized[resourceName] then + resourceTracker.initialized[resourceName] = true + resourceTracker.caches[resourceName] = resourceTracker.caches[resourceName] or {} + resourceTracker.callbacks[resourceName] = resourceTracker.callbacks[resourceName] or {} + + AddEventHandler('onResourceStop', function(stoppingResource) + if stoppingResource ~= resourceName then return end + + -- Clean up caches + for _, cacheName in ipairs(resourceTracker.caches[resourceName] or {}) do + if Cache.Caches[cacheName] then + Cache.Caches[cacheName] = nil + debugPrint(("Removed cache '%s' - resource '%s' stopped"):format(cacheName, resourceName)) + end + end + + -- Clean up callbacks + for _, cb in ipairs(resourceTracker.callbacks[resourceName] or {}) do + local targetCache = Cache.Caches[cb.cacheName] + if targetCache then + table.remove(targetCache.OnChange, cb.index) + debugPrint(("Removed OnChange callback from cache '%s' - resource '%s' stopped"):format( + cb.cacheName, + resourceName + )) + end + end + + -- Clear tracking data + resourceTracker.caches[resourceName] = nil + resourceTracker.callbacks[resourceName] = nil + resourceTracker.initialized[resourceName] = nil + end) + end + + -- Track the new item + if type == "cache" then + table.insert(resourceTracker.caches[resourceName], data) + elseif type == "callback" then + table.insert(resourceTracker.callbacks[resourceName], data) + end +end + ---@param name string ---@param compare fun():any ---@param waitTime integer | nil @@ -129,6 +181,10 @@ function Cache.Create(name, compare, waitTime) OnChange = {}, Value = result } + + -- Track the cache with its resource + trackResource(GetInvokingResource(), "cache", _name) + Cache.Caches[_name] = newCache debugPrint(_name .. " created with initial value: " .. tostring(result)) @@ -159,47 +215,35 @@ function Cache.OnChange(name, onChange) local cache = Cache.Caches[_name] assert(cache, "Cache with name '" .. _name .. "' does not exist.") + local id = Id.CreateUniqueId(Cache.Caches[_name]?.OnChange) -- Figure out which resource is trying to register this callback local invokingResource = GetInvokingResource() if not invokingResource then return end - - -- Make sure we have a place to store callbacks for this resource - resourceCallbacks[invokingResource] = resourceCallbacks[invokingResource] or {} - -- Add the new callback to our list - local callbackIndex = #cache.OnChange + 1 + local callbackIndex = id cache.OnChange[callbackIndex] = onChange - -- Keep track of this callback so we can clean it up later - table.insert(resourceCallbacks[invokingResource], { + -- Track the callback with its resource + trackResource(GetInvokingResource(), "callback", { cacheName = _name, index = callbackIndex }) - -- Watch for when the resource stops and clean up its callbacks - AddEventHandler('onResourceStop', function(resourceName) - if resourceName == invokingResource then - -- Clean up any callbacks this resource registered - local callbacks = resourceCallbacks[resourceName] - if callbacks then - for _, cb in ipairs(callbacks) do - local targetCache = Cache.Caches[cb.cacheName] - if targetCache then - -- Remove the callback from our list - table.remove(targetCache.OnChange, cb.index) - debugPrint(("Removed OnChange callback from cache '%s' - resource '%s' stopped"):format( - cb.cacheName, - resourceName - )) - end - end - -- Clear out all callbacks for this resource - resourceCallbacks[resourceName] = nil - end - end - end) - debugPrint(("Added new OnChange callback to cache '%s' from resource '%s'"):format(_name, invokingResource)) + return callbackIndex +end + +function Cache.RemoveOnChange(name, id) + assert(name, "Cache name is required.") + local _name = tostring(name) + local cache = Cache.Caches[_name] + assert(cache, "Cache with name '" .. _name .. "' does not exist.") + if cache.OnChange[id] then + cache.OnChange[id] = nil + debugPrint("Removed OnChange callback from cache '" .. _name .. "' with ID: " .. id) + else + debugPrint("No OnChange callback found with ID: " .. id .. " in cache '" .. _name .. "'") + end end ---@param name string @@ -232,4 +276,4 @@ function Cache.Update(name, newValue) end end -return Cache +return Cache \ No newline at end of file diff --git a/lib/entities/client/client_entity.lua b/lib/entities/client/client_entity.lua index d3764ff..bcda856 100644 --- a/lib/entities/client/client_entity.lua +++ b/lib/entities/client/client_entity.lua @@ -13,40 +13,36 @@ local function SpawnEntity(entityData) -- print(string.format("SpawnEntity %s: %s", k, v)) -- end local model = entityData.model and type(entityData.model) == 'string' and GetHashKey(entityData.model) or entityData.model - if not Utility.LoadModel(model) then + if model and not Utility.LoadModel(model) then print(string.format("[ClientEntity] Failed to load model %s for entity %s", entityData.model, entityData.id)) return end local entity = nil local coords = entityData.coords - local rotation = entityData.rotation + local rotation = entityData.rotation or vector3(0.0, 0.0, 0.0) -- Default rotation if not provided if entityData.entityType == 'object' then entity = CreateObject(model, coords.x, coords.y, coords.z, false, false, false) SetEntityRotation(entity, rotation.x, rotation.y, rotation.z, 2, true) elseif entityData.entityType == 'ped' then entity = CreatePed(4, model, coords.x, coords.y, coords.z, type(rotation) == 'number' and rotation or rotation.z, false, false) - -- Apply ped specific settings from entityData.meta if needed elseif entityData.entityType == 'vehicle' then entity = CreateVehicle(model, coords.x, coords.y, coords.z, type(rotation) == 'number' and rotation or rotation.z, false, false) - -- Apply vehicle specific settings from entityData.meta if needed else print(string.format("[ClientEntity] Unknown entity type '%s' for entity %s", entityData.entityType, entityData.id)) end - if entity then - -- print(string.format("[ClientEntity] Spawned %s entity %s (GameID: %s)", entityData.entityType, entityData.id, entity)) + if entity and model then entityData.spawned = entity SetModelAsNoLongerNeeded(model) - SetEntityAsMissionEntity(entity, true, true) -- Keep entity from being deleted by game engine - FreezeEntityPosition(entity, true) -- Optional freeze based on meta - if entityData.OnSpawn and type(entityData.OnSpawn) == 'function' then - entityData.OnSpawn(entityData) - end - -- print(string.format("[ClientEntity] Spawned %s entity %s (GameID: %s)", entityData.entityType, entityData.id, entity)) + SetEntityAsMissionEntity(entity, true, true) + FreezeEntityPosition(entity, true) else SetModelAsNoLongerNeeded(model) end + if entityData.OnSpawn then + entityData.OnSpawn(entityData) + end end local function RemoveEntity(entityData) @@ -59,7 +55,7 @@ local function RemoveEntity(entityData) SetEntityAsMissionEntity(entityHandle, false, false) DeleteEntity(entityHandle) end - if entityData.OnRemove and type(entityData.OnRemove) == 'function' then + if entityData.OnRemove then entityData.OnRemove(entityData) end end @@ -74,7 +70,7 @@ function ClientEntity.Register(entityData) -- Use Point system for proximity checks -- print(string.format("[ClientEntity] Registering entity %s at %s", entityData.id, json.encode(entityData))) - Point.Register(entityData.id, entityData.coords, entityData.spawnDistance or 50.0, entityData, SpawnEntity, RemoveEntity, function() end) + return Point.Register(entityData.id, entityData.coords, entityData.spawnDistance or 50.0, entityData, SpawnEntity, RemoveEntity, function() end) end --- Unregisters an entity and removes it from the world if spawned. @@ -83,8 +79,8 @@ function ClientEntity.Unregister(id) local entityData = Entities[id] if not entityData then return end - Point.Remove(id) - RemoveEntity(entityData) + Point.Remove(id) + RemoveEntity(entityData) Entities[id] = nil end @@ -193,7 +189,7 @@ end) RegisterNetEvent("community_bridge:client:TriggerEntityActions", function(entityId, actions, endPosition) local entityData = Entities[entityId] if entityData then - for _, actionData in pairs(actions) do + for _, actionData in pairs(actions) do local actionName = actionData.name local actionParams = actionData.params if actionName == "Stop" then diff --git a/lib/init.lua b/lib/init.lua index ef0d786..e22e837 100644 --- a/lib/init.lua +++ b/lib/init.lua @@ -2,7 +2,7 @@ loadedModules = {} function Require(modulePath, resourceName) if resourceName and type(resourceName) ~= "string" then - resourceName = GetCurrentResourceName() + resourceName = GetInvokingResource() end if not resourceName then @@ -62,14 +62,14 @@ cLib.Cache = Cache or Require("lib/cache/shared/cache.lua") cLib.ServerEntity = ServerEntity or Require("lib/entities/server/server_entity.lua") cLib.Marker = Marker or Require("lib/markers/server/server.lua") cLib.Particle = Particle or Require("lib/particles/server/particles.lua") +cLib.Shell = Shells or Require("lib/shells/server/shells.lua") if IsDuplicityVersion() then return cLib end ::client:: -cLib.Gizmo = Gizmo or Require("lib/placers/client/gizmo.lua") cLib.Scaleform = Scaleform or Require("lib/scaleform/client/scaleform.lua") cLib.Placeable = Placeable or Require("lib/placers/client/object_placer.lua") cLib.Utility = Utility or Require("lib/utility/client/utility.lua") -cLib.PlaceableObject = PlaceableObject or Require("lib/placers/client/placeable_object.lua") +cLib.PlaceableObject = ObjectPlacer or Require("lib/placers/client/placeable_object.lua") cLib.Raycast = Raycast or Require("lib/raycast/client/raycast.lua") cLib.Point = Point or Require("lib/points/client/points.lua") cLib.Particle = Particle or Require("lib/particles/client/particles.lua") diff --git a/lib/placers/client/dataview.lua b/lib/placers/client/dataview.lua deleted file mode 100644 index df99803..0000000 --- a/lib/placers/client/dataview.lua +++ /dev/null @@ -1,154 +0,0 @@ -local dataView = setmetatable({ - EndBig = ">", - EndLittle = "<", - Types = { - Int8 = { code = "i1" }, - Uint8 = { code = "I1" }, - Int16 = { code = "i2" }, - Uint16 = { code = "I2" }, - Int32 = { code = "i4" }, - Uint32 = { code = "I4" }, - Int64 = { code = "i8" }, - Uint64 = { code = "I8" }, - Float32 = { code = "f", size = 4 }, -- a float (native size) - Float64 = { code = "d", size = 8 }, -- a double (native size) - - LuaInt = { code = "j" }, -- a lua_Integer - UluaInt = { code = "J" }, -- a lua_Unsigned - LuaNum = { code = "n" }, -- a lua_Number - String = { code = "z", size = -1, }, -- zero terminated string - }, - - FixedTypes = { - String = { code = "c" }, -- a fixed-sized string with n bytes - Int = { code = "i" }, -- a signed int with n bytes - Uint = { code = "I" }, -- an unsigned int with n bytes - }, -}, { - __call = function(_, length) - return dataView.ArrayBuffer(length) - end -}) -dataView.__index = dataView - ---[[ Create an ArrayBuffer with a size in bytes --]] -function dataView.ArrayBuffer(length) - return setmetatable({ - blob = string.blob(length), - length = length, - offset = 1, - cangrow = true, - }, dataView) -end - ---[[ Wrap a non-internalized string --]] -function dataView.Wrap(blob) - return setmetatable({ - blob = blob, - length = blob:len(), - offset = 1, - cangrow = true, - }, dataView) -end - ---[[ Return the underlying bytebuffer --]] -function dataView:Buffer() return self.blob end -function dataView:ByteLength() return self.length end -function dataView:ByteOffset() return self.offset end -function dataView:SubView(offset, length) - return setmetatable({ - blob = self.blob, - length = length or self.length, - offset = 1 + offset, - cangrow = false, - }, dataView) -end - ---[[ Return the Endianness format character --]] -local function ef(big) return (big and dataView.EndBig) or dataView.EndLittle end - ---[[ Helper function for setting fixed datatypes within a buffer --]] -local function packblob(self, offset, value, code) - -- If cangrow is false the dataview represents a subview, i.e., a subset - -- of some other string view. Ensure the references are the same before - -- updating the subview - local packed = self.blob:blob_pack(offset, code, value) - if self.cangrow or packed == self.blob then - self.blob = packed - self.length = packed:len() - return true - else - return false - end -end - ---[[ - Create the API by using dataView.Types ---]] -for label,datatype in pairs(dataView.Types) do - if not datatype.size then -- cache fixed encoding size - datatype.size = string.packsize(datatype.code) - elseif datatype.size >= 0 and string.packsize(datatype.code) ~= datatype.size then - local msg = "Pack size of %s (%d) does not match cached length: (%d)" - error(msg:format(label, string.packsize(datatype.code), datatype.size)) - return nil - end - - dataView["Get" .. label] = function(self, offset, endian) - offset = offset or 0 - if offset >= 0 then - local o = self.offset + offset - local v,_ = self.blob:blob_unpack(o, ef(endian) .. datatype.code) - return v - end - return nil - end - - dataView["Set" .. label] = function(self, offset, value, endian) - if offset >= 0 and value then - local o = self.offset + offset - local v_size = (datatype.size < 0 and value:len()) or datatype.size - if self.cangrow or ((o + (v_size - 1)) <= self.length) then - if not packblob(self, o, value, ef(endian) .. datatype.code) then - error("cannot grow subview") - end - else - error("cannot grow dataview") - end - end - return self - end -end - -for label,datatype in pairs(dataView.FixedTypes) do - datatype.size = -1 -- Ensure cached encoding size is invalidated - - dataView["GetFixed" .. label] = function(self, offset, typelen, endian) - if offset >= 0 then - local o = self.offset + offset - if (o + (typelen - 1)) <= self.length then - local code = ef(endian) .. "c" .. tostring(typelen) - local v,_ = self.blob:blob_unpack(o, code) - return v - end - end - return nil -- Out of bounds - end - - dataView["SetFixed" .. label] = function(self, offset, typelen, value, endian) - if offset >= 0 and value then - local o = self.offset + offset - if self.cangrow or ((o + (typelen - 1)) <= self.length) then - local code = ef(endian) .. "c" .. tostring(typelen) - if not packblob(self, o, value, code) then - error("cannot grow subview") - end - else - error("cannot grow dataview") - end - end - return self - end -end - -return dataView \ No newline at end of file diff --git a/lib/placers/client/gizmo.lua b/lib/placers/client/gizmo.lua deleted file mode 100644 index 7bb1010..0000000 --- a/lib/placers/client/gizmo.lua +++ /dev/null @@ -1,347 +0,0 @@ - --- CREDITS --- Andyyy7666: https://github.com/overextended/ox_lib/pull/453 --- AvarianKnight: https://forum.cfx.re/t/allow-drawgizmo-to-be-used-outside-of-fxdk/5091845/8?u=demi-automatic -local dataview = Require("lib/placers/client/dataview.lua") -local enableScale = false -- allow scaling mode. doesnt scale collisions and resets when physics are applied it seems -local gizmoEnabled = false -local currentMode = 'translate' -local isRelative = false -local currentEntity - --- FUNCTIONS - - -local function normalize(x, y, z) - local length = math.sqrt(x * x + y * y + z * z) - if length == 0 then - return 0, 0, 0 - end - return x / length, y / length, z / length -end - -local function makeEntityMatrix(entity) - local f, r, u, a = GetEntityMatrix(entity) - local view = dataview.ArrayBuffer(60) - - view:SetFloat32(0, r[1]) - :SetFloat32(4, r[2]) - :SetFloat32(8, r[3]) - :SetFloat32(12, 0) - :SetFloat32(16, f[1]) - :SetFloat32(20, f[2]) - :SetFloat32(24, f[3]) - :SetFloat32(28, 0) - :SetFloat32(32, u[1]) - :SetFloat32(36, u[2]) - :SetFloat32(40, u[3]) - :SetFloat32(44, 0) - :SetFloat32(48, a[1]) - :SetFloat32(52, a[2]) - :SetFloat32(56, a[3]) - :SetFloat32(60, 1) - - return view -end - -local function applyEntityMatrix(entity, view) - local x1, y1, z1 = view:GetFloat32(16), view:GetFloat32(20), view:GetFloat32(24) - local x2, y2, z2 = view:GetFloat32(0), view:GetFloat32(4), view:GetFloat32(8) - local x3, y3, z3 = view:GetFloat32(32), view:GetFloat32(36), view:GetFloat32(40) - local tx, ty, tz = view:GetFloat32(48), view:GetFloat32(52), view:GetFloat32(56) - - if not enableScale then - x1, y1, z1 = normalize(x1, y1, z1) - x2, y2, z2 = normalize(x2, y2, z2) - x3, y3, z3 = normalize(x3, y3, z3) - end - - SetEntityMatrix(entity, - x1, y1, z1, - x2, y2, z2, - x3, y3, z3, - tx, ty, tz - ) -end - -function InBoundary(pos, boundary) - if not boundary then return false end - local x, y, z = table.unpack(pos) - local minX, minY, minZ = table.unpack(boundary.min) - local maxX, maxY, maxZ = table.unpack(boundary.max) - return x >= minX and x <= maxX and y >= minY and y <= maxY and z >= minZ and z <= maxZ -end - --- LOOPS - -function RegisterButtonHandler(button, onPressed, onReleased) - onPressed = onPressed and type(onPressed) == 'function' and onPressed - onReleased = onReleased and type(onReleased) == 'function' and onReleased - DisableControlAction(0, button, true) - local pressed = IsDisabledControlJustPressed(0, button) - local released = IsDisabledControlJustReleased(0, button) - return (pressed and onPressed and onPressed()) or (released and onReleased and onReleased()) -end - - -local function gizmoLoop(entity, onConfirm, onUpdate, onCancel, settings) - assert(entity, 'entity is required') - entity = tonumber(entity) - EnterCursorMode() - settings = settings or {} - local allowedMats = settings.allowedMats - local maxDepth = settings.maxDepth or 10 - local outLine = false - - if IsEntityAPed(entity) then - SetEntityAlpha(entity, 200) - end - - if allowedMats or boundary then - CreateThread(function() - while gizmoEnabled do - local coords = GetEntityCoords(entity) - local destination = coords - vector3(0, 0, maxDepth) - local hit, _, _, _, materialHash = Raycast.ToCoords(coords, destination, 1, 4) - if hit and hit ~=1 and (allowedMats?[materialHash] or InBoundary(GetEntityCoords(entity), boundary)) then - if not inBounds then - inBounds = true - SetEntityDrawOutlineColor(0, 255, 0, 255) - SetEntityDrawOutline(entity, true) - end - elseif inBounds then - inBounds = false - SetEntityDrawOutline(entity, false) - end - Wait(500) - end - end) - end - - while gizmoEnabled and DoesEntityExist(entity) do - Wait(0) - - DisableControlAction(0, 24, true) -- lmb - DisableControlAction(0, 25, true) -- rmb - DisableControlAction(0, 140, true) -- r - DisableControlAction(0, 245, true) --t - DisablePlayerFiring(PlayerId(), true) - SetEntityCollision(entity, false, false) - FreezeEntityPosition(entity, false) - local matrixBuffer = makeEntityMatrix(entity) - local changed = Citizen.InvokeNative(0xEB2EDCA2, matrixBuffer:Buffer(), 'Editor1', Citizen.ReturnResultAnyway()) - if changed then - applyEntityMatrix(entity, matrixBuffer) - local coords = GetEntityCoords(entity) - SetEntityCoords(entity, coords.x, coords.y, coords.z, false, false, false, false) - end - - if onUpdate and type(onUpdate) == 'function' then onUpdate(entity, GetEntityCoords(entity), GetEntityRotation(entity)) end - --controles - --frontend confirm 18 [ENTER] - RegisterButtonHandler(191, function() - if not gizmoEnabled then return end - gizmoEnabled = false - if onConfirm and type(onConfirm) == 'function' then onConfirm(entity, GetEntityCoords(entity), GetEntityRotation(entity)) end - end) - --frontend cancel 202 [BACKSPACE] - RegisterButtonHandler(202, function() - if not gizmoEnabled then return end - gizmoEnabled = false - if onCancel and type(onCancel) == 'function' then onCancel(entity, GetEntityCoords(entity), GetEntityRotation(entity)) end - CreateThread(function() - local timeout = 100 - while timeout > 0 do - DisableFrontendThisFrame() - timeout = timeout - 1 - Wait(1) - end - end) - end) - --register e - RegisterButtonHandler(38, function() - if not gizmoEnabled then return end - gizmoEnabled = false - local playerPos = GetEntityCoords(PlayerPedId()) - local entityPos = GetFinalRenderedCamCoord() - local depth = #(playerPos - entityPos) -- Vector3 distance - settings.depth = depth - PlaceableObject.Create({spawned = entity}, nil, onConfirm, onUpdate, onCancel, settings) - end) - - --ctrl - RegisterButtonHandler(36, function() - if not gizmoEnabled then return end - LeaveCursorMode() - end, function() - EnterCursorMode() - end) - - RegisterButtonHandler(19, function() - if not gizmoEnabled then return end - PlaceObjectOnGroundProperly_2(currentEntity) - end) - FreezeEntityPosition(entity, false) - end - - LeaveCursorMode() - - if DoesEntityExist(entity) then - if IsEntityAPed(entity) then SetEntityAlpha(entity, 255) end - SetEntityDrawOutline(entity, false) - end - - gizmoEnabled = false - currentEntity = nil - return true -end - ---=================================================== --- █▀ █ █ ▄▀▀ █▄▀ ▀▄▀ ▄▀▄ █ █ █▄ █ ██▀ █ █ ██▄ --- █▀ ▀▄█ ▀▄▄ █ █ █ ▀▄▀ ▀▄█ █ ▀█ █▄▄ ▀▄▀▄▀ █▄█ ---=================================================== --- .--------. --- | taktak | --- |/-------' --- .-. ,-. --- ;oo oo; --- / \| |/ \ --- |. `. .' .| --- `;.;' `;.;' --- .-^-. .-^-. ko1 - --- local function textUILoop() --- CreateThread(function() --- while gizmoEnabled do --- Wait(100) --- local scaleText = (enableScale and '[S] - Scale Mode \n') or '' --- lib.showTextUI( --- ('Current Mode: %s | %s \n'):format(currentMode, (isRelative and 'Relative') or 'World') .. --- '[W] - Translate Mode \n' .. --- '[R] - Rotate Mode \n' .. --- scaleText .. --- '[Q] - Relative/World \n' .. --- '[LALT] - Snap To Ground \n' .. --- '[ENTER] - Done Editing \n' --- ) --- end --- lib.hideTextUI() --- end) --- end - --- EXPORTS - - -local function useGizmo(entity, onConfirm, onUpdate, onCancel, settings) - gizmoEnabled = true - currentEntity = entity - -- textUILoop() - gizmoLoop(entity, onConfirm, onUpdate, onCancel, settings) - - return { - handle = entity, - position = GetEntityCoords(entity), - rotation = GetEntityRotation(entity) - } -end - -exports("useGizmo", useGizmo) - -Gizmo = {} -local running = false -function Gizmo.UseGizmo(obj, onConfirm, onUpdate, onCancel, settings) - if running then return end - running = true - - --instructional buttons - local scaleform = Scaleform.SetupInstructionalButtons({ - {type = "CLEAR_ALL"}, - {type = "SET_CLEAR_SPACE", int = 200}, - {type = "SET_DATA_SLOT", name = 'Translate:', keyIndex = {245}, int = 1}, - {type = "SET_DATA_SLOT", name = 'Scale:', keyIndex = {33}, int = 2}, - {type = "SET_DATA_SLOT", name = 'Rotate:', keyIndex = {45}, int = 3}, - {type = "SET_DATA_SLOT", name = 'Snap to Ground:', keyIndex = {19}, int = 4}, - {type = "SET_DATA_SLOT", name = 'Toggle Camera:', keyIndex = {36}, int = 5}, - {type = "SET_DATA_SLOT", name = 'Cancel Placement:', keyIndex = {202}, int = 6}, - {type = "SET_DATA_SLOT", name = 'Toggle Gizmo:', keyIndex = {38}, int = 7}, - {type = "DRAW_INSTRUCTIONAL_BUTTONS"}, - {type = "SET_BACKGROUND_COLOUR"}, - }) - local quit = false - CreateThread(function() - while not quit do - DrawScaleformMovieFullscreen(scaleform, 255, 255, 255, 255, 0) - Wait(0) - end - running = false - end) - - quit = useGizmo(obj, onConfirm, onUpdate, onCancel, settings) - running = false -end -exports("UseGizmo", Gizmo.UseGizmo) - - ---got rid of the cancer --- lib.addKeybind({ --- name = '_gizmoLocal', --- description = 'toggle gizmo to be local to the entity instead of world', --- defaultKey = 'Q', --- onPressed = function(self) --- if not gizmoEnabled then return end --- isRelative = not isRelative --- ExecuteCommand('+gizmoLocal') --- end, --- onReleased = function (self) --- ExecuteCommand('-gizmoLocal') --- end --- }) - --- lib.addKeybind({ --- name = 'gizmoclose', --- description = 'close gizmo', --- defaultKey = 'RETURN', --- onPressed = function(self) --- if not gizmoEnabled then return end --- gizmoEnabled = false --- end, --- }) - --- lib.addKeybind({ --- name = 'gizmoSnapToGround', --- description = 'snap current gizmo object to floor/surface', --- defaultKey = 'LMENU', --- onPressed = function(self) --- if not gizmoEnabled then return end --- PlaceObjectOnGroundProperly_2(currentEntity) --- end, --- }) - --- if enableScale then --- lib.addKeybind({ --- name = '_gizmoScale', --- description = 'Sets mode for the gizmo to scale', --- defaultKey = 'S', --- onPressed = function(self) --- if not gizmoEnabled then return end --- currentMode = 'Scale' --- ExecuteCommand('+gizmoScale') --- end, --- onReleased = function (self) --- ExecuteCommand('-gizmoScale') --- end --- }) --- end - - ---onreousrcestop - -AddEventHandler('onResourceStop', function(resource) - if resource == GetCurrentResourceName() then - if not gizmoEnabled then return end - gizmoEnabled = false - LeaveCursorMode() - end -end) - -return Gizmo \ No newline at end of file diff --git a/lib/placers/client/object_Placer.lua b/lib/placers/client/object_Placer.lua index a56dea8..70891be 100644 --- a/lib/placers/client/object_Placer.lua +++ b/lib/placers/client/object_Placer.lua @@ -6,10 +6,10 @@ lib.locale() -- Object placer -- local placementText = { - locale('place_object_place'), - locale('place_object_cancel'), - locale('place_object_scroll_up'), - locale('place_object_scroll_down') + locale('placeable_object.place_object_place'), + locale('placeable_object.place_object_cancel'), + locale('placeable_object.place_object_scroll_up'), + locale('placeable_object.place_object_scroll_down') } local function finishPlacing() @@ -31,7 +31,7 @@ Placeable.PlaceObject = function(object, distance, snapToGround, allowedMats, of distance = tonumber(distance or 10.0 ) if activePlacementProp then return end - if not object then Prints.Error('no_prop_defined') end + if not object then Prints.Error('placeable_object.no_prop_defined') end local propObject = type(object) == 'string' and joaat(object) or object local heading = 0.0 diff --git a/lib/placers/client/placeable_object.lua b/lib/placers/client/placeable_object.lua index 26b10c5..5a333eb 100644 --- a/lib/placers/client/placeable_object.lua +++ b/lib/placers/client/placeable_object.lua @@ -1,16 +1,18 @@ Scaleform = Scaleform or Require("lib/scaleform/client/scaleform.lua") Utility = Utility or Require("lib/utility/client/utility.lua") -Gizmo = Gizmo or Require("lib/placers/client/gizmo.lua") Raycast = Raycast or Require("lib/raycast/client/raycast.lua") +Language = Language or Require("modules/locales/shared.lua") PlaceableObject = PlaceableObject or {} -local data = { - entity = nil, - placing = false, -} +-- Local variables +local isPlacing = false +local currentEntity = nil +local currentMode = 'normal' -- 'normal' or 'movement' +local currentPromise = nil -- Store the current promise -function PlaceableObject.Eyetrace(depth, disableSphere) +-- Utility functions +local function eyetrace(depth, disableSphere) local screenX = GetDisabledControlNormal(0, 239) local screenY = GetDisabledControlNormal(0, 240) @@ -23,171 +25,555 @@ function PlaceableObject.Eyetrace(depth, disableSphere) return target end -function PlaceableObject.InBoundary(pos, boundary) - if not boundary then return false end +local function inBoundary(pos, boundary) + if not boundary then return true end local x, y, z = table.unpack(pos) local minX, minY, minZ = table.unpack(boundary.min) local maxX, maxY, maxZ = table.unpack(boundary.max) return x >= minX and x <= maxX and y >= minY and y <= maxY and z >= minZ and z <= maxZ end --- Creates a placeable object in the game world. --- @param model (string) The model of the object to create. --- @param onConfirm (function) [optional] The callback function to execute when the object is confirmed. --- @param onUpdate (function) [optional] The callback function to execute when the object is moved. --- @param onCancel (function) [optional] The callback function to execute when the object is canceled. --- @param settings (table) [optional] Additional settings for the placeable object. --- - depthMin (number) The minimum depth for the object placement. Default is 2.0. --- - depthMax (number) The maximum depth for the object placement. Default is 10.0. --- - rotationStep (number) The rotation step for the object. Default is 15.0. --- - depthStep (number) The depth step for the object. Default is 1.0. -function PlaceableObject.Create(data, model, onConfirm, onUpdate, onCancel, settings) - local settings = settings or {} - local depthMin = settings.depthMin or 2.0 - depthMax = settings.depthMax or 10.0 - rotationStep = settings.rotationStep or 15.0 - depthStep = settings.depthStep or 1.0 - disableSphere = settings.useSphere and false or true - local depth = settings.depth or 10.0 - data.placing = true - data.paused = false - local initialPos = nil - local placeOnGround = true - local allowedMats = settings.allowedMats - local boundary = settings.boundary - local config = settings.config or {} - --scaleform - local scaleform = Scaleform.SetupInstructionalButtons({ - {type = "CLEAR_ALL"}, - {type = "SET_CLEAR_SPACE", int = 200}, - {type = "SET_DATA_SLOT", name = config?.place_object?.name or 'Place Object:', keyIndex = config?.place_object?.key or {223}, int = 5}, - {type = "SET_DATA_SLOT", name = config?.cancel_placement?.name or 'Cancel Placement:', keyIndex = config?.cancel_placement?.key or {222}, int = 4}, - {type = "SET_DATA_SLOT", name = config?.snap_to_ground?.name or 'Snap to Ground:', keyIndex = config?.snap_to_ground?.key or {19}, int = 1}, - {type = "SET_DATA_SLOT", name = config?.rotate?.name or 'Rotate:', keyIndex = config?.rotate?.key or {14, 15}, int = 2}, - {type = "SET_DATA_SLOT", name = config?.distance?.name or 'Distance:', keyIndex = config?.distance?.key or {14,15,36}, int = 3}, - {type = "SET_DATA_SLOT", name = config?.toggle_placement?.name or 'Toggle Placement:', keyIndex = config?.toggle_placement?.key or {199}, int = 0}, - {type = "SET_DATA_SLOT", name = config?.gizmo?.name or 'Toggle Gizmo:', keyIndex = config?.gizmo?.key or {38}, int = 6}, - {type = "DRAW_INSTRUCTIONAL_BUTTONS"}, - {type = "SET_BACKGROUND_COLOUR"}, - }) - local heading = -GetEntityHeading(PlayerPedId()) - - local pos = PlaceableObject.Eyetrace(depth, disableSphere) - if not data.spawned and model then - --get player heading - local obj = Utility.CreateProp(model, pos, vector3(0, 0, heading), nil) - data.spawned = obj - end - assert(data.spawned, "Failed to create object") - SetEntityCollision(data.spawned, false, false) - SetEntityAlpha(data.spawned, 150, false) - - SetPedConfigFlag(PlayerPedId(), 146, true) - SetCanClimbOnEntity(data.spawned, false) - SetEntityCompletelyDisableCollision(data.spawned, true, false) - SetEntityNoCollisionEntity(PlayerPedId(), data.spawned, false) +local function checkBoundaryAndMaterials(entity, settings) local inBounds = true - if allowedMats or boundary then + if settings.allowedMats or settings.boundary then CreateThread(function() - while data.placing do - local hit, _, coords, _, materialHash = Raycast.FromCamera(1, 4) - if hit and hit ~=1 and (allowedMats?[materialHash] or PlaceableObject.InBoundary(GetEntityCoords(data.spawned), boundary)) then + while isPlacing do + local hit, _, coords, _, materialHash + + if currentMode == 'movement' then + local entityCoords = GetEntityCoords(entity) + local destination = entityCoords - vector3(0, 0, settings.maxDepth or 10) + hit, _, coords, _, materialHash = Raycast.ToCoords(entityCoords, destination, 1, 4) + else + hit, _, coords, _, materialHash = Raycast.FromCamera(1, 4) + end + + local validMaterial = not settings.allowedMats or settings.allowedMats[materialHash] + local validBoundary = inBoundary(GetEntityCoords(entity), settings.boundary) + + if hit and hit ~= 1 and validMaterial and validBoundary then if not inBounds then inBounds = true SetEntityDrawOutlineColor(0, 255, 0, 255) - SetEntityDrawOutline(data.spawned, true) + SetEntityDrawOutline(entity, true) end elseif inBounds then inBounds = false - SetEntityDrawOutline(data.spawned, false) + SetEntityDrawOutline(entity, false) end Wait(500) end + SetEntityDrawOutline(entity, false) end) end - - CreateThread(function() - while data.placing do - if data.paused then goto continue end - DrawScaleformMovieFullscreen(scaleform, 255, 255, 255, 255, 0) - DisableControlAction(0, 24, true) -- Attack - DisableControlAction(0, 25, true) -- Aim - DisableControlAction(0, 36, true) -- INPUT_DUCK. - - if IsDisabledControlJustPressed(0, 223) then -- left click - if not inBounds then - Notify.SendNotify("You can't place this object here", "error", 5000) - elseif onConfirm then - onConfirm(data.spawned, pos, heading) - data.placing = false - end - end - - if IsDisabledControlJustPressed(0, 25) then -- right click - data.placing = false - if onCancel then - onCancel(data.spawned, pos, heading) - else - DeleteEntity(data.spawned) - end - return - end - - if IsControlJustPressed(0,19) then - placeOnGround = not placeOnGround - end - - if IsControlJustPressed(0, 38) then -- TAB key to switch to gizmo - data.placing = false - return Gizmo.UseGizmo(data.spawned, onConfirm, onUpdate, onCancel, settings) - end - - if IsControlPressed(0,224) then -- left ctrl - if IsControlJustPressed(0, 261) then -- scroll up - depth = depth + depthStep - if depth > depthMax then - depth = depthMax - end - end - - if IsControlJustPressed(0, 262) then -- scroll down - depth = depth - depthStep - if depth < depthMin then - depth = depthMin - end - end - else - if IsControlJustPressed(0, 261) then -- scroll up - heading = heading + rotationStep - if heading > 360 then - heading = 0 - end - end - if IsControlJustPressed(0, 262) then -- scroll down - heading = heading - rotationStep - if heading < 0 then - heading = 360 - end - end - end - - pos = PlaceableObject.Eyetrace(depth, disableSphere) - if data.spawned then - SetEntityCoords(data.spawned, pos.x, pos.y, pos.z) - SetEntityHeading(data.spawned, heading) - if placeOnGround then - PlaceObjectOnGroundProperly(data.spawned) - pos = GetEntityCoords(data.spawned) - end - end - if onUpdate and type(onUpdate) == 'function' then onUpdate(data.spawned, pos, heading) end - ::continue:: - if IsControlJustPressed(0, 199) then -- home - data.paused = not data.paused - end - Wait(1) - end - end) + return function() return inBounds end end +local function setupInstructionalButtons(settings) + local buttons = { + {type = "CLEAR_ALL"}, + {type = "SET_CLEAR_SPACE", int = 200}, + } + + -- Common buttons + table.insert(buttons, {type = "SET_DATA_SLOT", name = settings.config?.place_object?.name or 'Place Object:', keyIndex = settings.config?.place_object?.key or {223}, int = 5}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = settings.config?.cancel_placement?.name or 'Cancel Placement:', keyIndex = settings.config?.cancel_placement?.key or {222}, int = 4}) + + if currentMode == 'normal' then + table.insert(buttons, {type = "SET_DATA_SLOT", name = settings.config?.snap_to_ground?.name or 'Snap to Ground:', keyIndex = settings.config?.snap_to_ground?.key or {19}, int = 1}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = settings.config?.rotate?.name or 'Rotate:', keyIndex = settings.config?.rotate?.key or {14, 15}, int = 2}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = settings.config?.distance?.name or 'Distance:', keyIndex = settings.config?.distance?.key or {14,15,36}, int = 3}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = settings.config?.toggle_placement?.name or 'Toggle Placement:', keyIndex = settings.config?.toggle_placement?.key or {199}, int = 0}) + + -- Add vertical controls if allowed + if settings.allowVertical then + table.insert(buttons, {type = "SET_DATA_SLOT", name = 'Move Up/Down:', keyIndex = {85, 48}, int = 8}) + end + + if settings.allowMovement then + table.insert(buttons, {type = "SET_DATA_SLOT", name = settings.config?.movement?.name or 'Toggle Movement Mode:', keyIndex = settings.config?.movement?.key or {38}, int = 6}) + end + elseif currentMode == 'movement' then + table.insert(buttons, {type = "SET_DATA_SLOT", name = 'Move Forward/Back:', keyIndex = {32, 33}, int = 1}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = 'Move Left/Right:', keyIndex = {34, 35}, int = 2}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = 'Move Up/Down:', keyIndex = {85, 48}, int = 3}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = 'Rotate Left/Right:', keyIndex = {174, 175}, int = 4}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = 'Snap to Ground:', keyIndex = {19}, int = 5}) + table.insert(buttons, {type = "SET_DATA_SLOT", name = 'Confirm (Enter):', keyIndex = {191}, int = 6}) + + if settings.allowNormal then + table.insert(buttons, {type = "SET_DATA_SLOT", name = 'Normal Mode:', keyIndex = {38}, int = 7}) + end + end + + table.insert(buttons, {type = "DRAW_INSTRUCTIONAL_BUTTONS"}) + table.insert(buttons, {type = "SET_BACKGROUND_COLOUR"}) + + return Scaleform.SetupInstructionalButtons(buttons) +end + +local function normalPlacementLoop(entity, settings, getBoundsStatus) + -- Initialize or retrieve from settings to maintain state + settings.currentDepth = settings.currentDepth or settings.depth or 10.0 + settings.currentHeading = settings.currentHeading or -GetEntityHeading(PlayerPedId()) + settings.currentHeight = settings.currentHeight or 0.0 -- Add height tracking + settings.placeOnGround = settings.placeOnGround ~= nil and settings.placeOnGround or not settings.allowVertical -- Default based on allowVertical + settings.paused = settings.paused or false + + local depth = settings.currentDepth + local heading = settings.currentHeading + local height = settings.currentHeight + local placeOnGround = settings.placeOnGround + local paused = settings.paused + local pos + + -- Don't use while loop here, just process one frame + if not isPlacing or currentMode ~= 'normal' then + return + end + + if paused then + if IsControlJustPressed(0, 199) then -- home + paused = not paused + settings.paused = paused + end + return + end + + -- Disable controls + DisableControlAction(0, 24, true) -- Attack + DisableControlAction(0, 25, true) -- Aim + DisableControlAction(0, 36, true) -- INPUT_DUCK + + -- Place object (left click) + if IsDisabledControlJustPressed(0, 223) then + if not getBoundsStatus() then + print(Language.Locale("placeable_object.cant_place_here")) + else + pos = GetEntityCoords(entity) + isPlacing = false + if currentPromise then + currentPromise:resolve({ + entity = entity, + position = pos, + heading = heading + }) + currentPromise = nil + end + DeleteEntity(entity) + return + end + end + + -- Cancel (right click) + if IsDisabledControlJustPressed(0, 25) then + isPlacing = false + if currentPromise then + currentPromise:resolve(nil) -- Return nil for cancel + currentPromise = nil + end + DeleteEntity(entity) + return + end + + -- Toggle snap to ground (Alt) + if IsControlJustPressed(0, 19) then + if settings.allowVertical then + placeOnGround = not placeOnGround + settings.placeOnGround = placeOnGround + if placeOnGround then + height = 0.0 -- Reset height when snapping to ground + settings.currentHeight = height + end + else + -- Force snap to ground if vertical movement not allowed + PlaceObjectOnGroundProperly(entity) + end + end + + -- Switch to movement mode + if settings.allowMovement and IsControlJustPressed(0, 38) then + currentMode = 'movement' + return + end + + -- Vertical controls (only if allowVertical is enabled and not snapped to ground) + if settings.allowVertical and not placeOnGround then + if IsControlPressed(0, 85) then -- Q - Move up + height = height + (settings.heightStep or 0.1) + settings.currentHeight = height + elseif IsControlPressed(0, 48) then -- Z - Move down + height = height - (settings.heightStep or 0.1) + settings.currentHeight = height + end + end + + -- Depth and rotation controls + if IsControlPressed(0, 224) then -- left ctrl + if IsControlJustPressed(0, 15) then -- D key + depth = math.min(depth + settings.depthStep, settings.depthMax) + elseif IsControlJustPressed(0, 14) then -- A key + depth = math.max(depth - settings.depthStep, settings.depthMin) + end + else + if IsControlJustPressed(0, 15) then -- D key + heading = (heading + settings.rotationStep) % 360 + elseif IsControlJustPressed(0, 14) then -- A key + heading = (heading - settings.rotationStep) % 360 + end + end + + -- Update position + pos = eyetrace(depth, settings.disableSphere) + + -- Add height offset if not snapping to ground + if settings.allowVertical and not placeOnGround then + pos = pos + vector3(0, 0, height) + end + + if entity then + SetEntityCoords(entity, pos.x, pos.y, pos.z) + SetEntityHeading(entity, heading) + if placeOnGround then + PlaceObjectOnGroundProperly(entity) + pos = GetEntityCoords(entity) + end + end + + -- Store updated values back to settings + settings.currentDepth = depth + settings.currentHeading = heading + settings.currentHeight = height + settings.placeOnGround = placeOnGround +end + +local function movementPlacementLoop(entity, settings, getBoundsStatus) + -- Don't use while loop here, just process one frame + if not isPlacing or currentMode ~= 'movement' or not DoesEntityExist(entity) then + return + end + + if IsEntityAPed(entity) then + SetEntityAlpha(entity, 200) + end + + -- Disable movement controls to prevent player from moving + DisableControlAction(0, 30, true) -- Move Left/Right + DisableControlAction(0, 31, true) -- Move Forward/Back + DisableControlAction(0, 36, true) -- INPUT_DUCK + DisableControlAction(0, 21, true) -- Sprint + DisableControlAction(0, 22, true) -- Jump + + SetEntityCollision(entity, false, false) + FreezeEntityPosition(entity, false) + + -- Get current entity position and rotation + local coords = GetEntityCoords(entity) + local heading = GetEntityHeading(entity) + local moved = false + + -- Movement speed settings + local moveSpeed = 0.1 + local fastMoveSpeed = 0.5 + local rotateSpeed = 2.0 + + -- Check if shift is held for faster movement + local isFastMode = IsControlPressed(0, 21) -- Left Shift + local currentMoveSpeed = isFastMode and fastMoveSpeed or moveSpeed + + -- Get camera rotation for relative movement + local camRot = GetGameplayCamRot(2) + local camHeading = math.rad(camRot.z) + + -- Calculate camera-relative directions + local camForward = vector3(-math.sin(camHeading), math.cos(camHeading), 0) + local camRight = vector3(math.cos(camHeading), math.sin(camHeading), 0) + + -- WASD movement (relative to camera direction) + if IsControlPressed(0, 32) then -- W - Move forward relative to camera + coords = coords + camForward * currentMoveSpeed + moved = true + elseif IsControlPressed(0, 33) then -- S - Move backward relative to camera + coords = coords - camForward * currentMoveSpeed + moved = true + end + + if IsControlPressed(0, 34) then -- A - Move left relative to camera + coords = coords - camRight * currentMoveSpeed + moved = true + elseif IsControlPressed(0, 35) then -- D - Move right relative to camera + coords = coords + camRight * currentMoveSpeed + moved = true + end + + -- Up/Down movement (always world-relative) + if settings.allowVertical and IsControlPressed(0, 85) then -- Q - Move up + coords = coords + vector3(0, 0, currentMoveSpeed) + moved = true + elseif settings.allowVertical and IsControlPressed(0, 48) then -- Z - Move down + coords = coords + vector3(0, 0, -currentMoveSpeed) + moved = true + end + + -- Rotation controls + if IsControlPressed(0, 174) then -- Left Arrow - Rotate left + heading = heading - rotateSpeed + moved = true + elseif IsControlPressed(0, 175) then -- Right Arrow - Rotate right + heading = heading + rotateSpeed + moved = true + end + + -- Alternative rotation with mouse wheel + if IsControlJustPressed(0, 241) then -- Mouse wheel up + heading = heading + 15.0 + moved = true + elseif IsControlJustPressed(0, 242) then -- Mouse wheel down + heading = heading - 15.0 + moved = true + end + + -- Apply movement if any occurred + if moved then + SetEntityCoords(entity, coords.x, coords.y, coords.z, false, false, false, false) + SetEntityHeading(entity, heading) + end + + -- Confirm placement (Enter) + if IsControlJustPressed(0, 191) then + if not getBoundsStatus() then + print(Language.Locale("placeable_object.cant_place_here")) + return + end + isPlacing = false + if currentPromise then + currentPromise:resolve({ + entity = entity, + position = GetEntityCoords(entity), + heading = GetEntityHeading(entity), + rotation = GetEntityRotation(entity) + }) + currentPromise = nil + end + DeleteEntity(entity) + return + end + + -- Cancel placement (Backspace) + if IsControlJustPressed(0, 202) then + isPlacing = false + if currentPromise then + currentPromise:resolve(nil) -- Return nil for cancel + currentPromise = nil + end + DeleteEntity(entity) + return + end + + -- Switch to normal mode (E) + if settings.allowNormal and IsControlJustPressed(0, 38) then + currentMode = 'normal' + local playerPos = GetEntityCoords(PlayerPedId()) + local entityPos = GetEntityCoords(entity) + local depth = #(playerPos - entityPos) + settings.currentDepth = depth + return + end + + -- Snap to ground (Alt) + if IsControlJustPressed(0, 19) then + PlaceObjectOnGroundProperly(entity) + end + + FreezeEntityPosition(entity, false) +end + +local function drawBoundaryBox(boundary) + if not boundary then return end + + local min = boundary.min + local max = boundary.max + + -- Define the 8 corners of the box + local corners = { + vector3(min.x, min.y, min.z), -- 1: bottom front left + vector3(max.x, min.y, min.z), -- 2: bottom front right + vector3(max.x, max.y, min.z), -- 3: bottom back right + vector3(min.x, max.y, min.z), -- 4: bottom back left + vector3(min.x, min.y, max.z), -- 5: top front left + vector3(max.x, min.y, max.z), -- 6: top front right + vector3(max.x, max.y, max.z), -- 7: top back right + vector3(min.x, max.y, max.z), -- 8: top back left + } + + -- Draw the box faces as triangles (2 triangles per face) + local alpha = 50 -- Semi-transparent + local r, g, b = 0, 255, 0 -- Green color + + -- Bottom face (looking up from below) + DrawPoly(corners[1].x, corners[1].y, corners[1].z, corners[2].x, corners[2].y, corners[2].z, corners[3].x, corners[3].y, corners[3].z, r, g, b, alpha) + DrawPoly(corners[1].x, corners[1].y, corners[1].z, corners[3].x, corners[3].y, corners[3].z, corners[4].x, corners[4].y, corners[4].z, r, g, b, alpha) + + -- Top face (looking down from above) + DrawPoly(corners[5].x, corners[5].y, corners[5].z, corners[7].x, corners[7].y, corners[7].z, corners[6].x, corners[6].y, corners[6].z, r, g, b, alpha) + DrawPoly(corners[5].x, corners[5].y, corners[5].z, corners[8].x, corners[8].y, corners[8].z, corners[7].x, corners[7].y, corners[7].z, r, g, b, alpha) + + -- Front face (min Y) + DrawPoly(corners[1].x, corners[1].y, corners[1].z, corners[5].x, corners[5].y, corners[5].z, corners[6].x, corners[6].y, corners[6].z, r, g, b, alpha) + DrawPoly(corners[1].x, corners[1].y, corners[1].z, corners[6].x, corners[6].y, corners[6].z, corners[2].x, corners[2].y, corners[2].z, r, g, b, alpha) + + -- Back face (max Y) + DrawPoly(corners[4].x, corners[4].y, corners[4].z, corners[7].x, corners[7].y, corners[7].z, corners[8].x, corners[8].y, corners[8].z, r, g, b, alpha) + DrawPoly(corners[4].x, corners[4].y, corners[4].z, corners[3].x, corners[3].y, corners[3].z, corners[7].x, corners[7].y, corners[7].z, r, g, b, alpha) + + -- Left face (min X) + DrawPoly(corners[1].x, corners[1].y, corners[1].z, corners[4].x, corners[4].y, corners[4].z, corners[8].x, corners[8].y, corners[8].z, r, g, b, alpha) + DrawPoly(corners[1].x, corners[1].y, corners[1].z, corners[8].x, corners[8].y, corners[8].z, corners[5].x, corners[5].y, corners[5].z, r, g, b, alpha) + + -- Right face (max X) + DrawPoly(corners[2].x, corners[2].y, corners[2].z, corners[6].x, corners[6].y, corners[6].z, corners[7].x, corners[7].y, corners[7].z, r, g, b, alpha) + DrawPoly(corners[2].x, corners[2].y, corners[2].z, corners[7].x, corners[7].y, corners[7].z, corners[3].x, corners[3].y, corners[3].z, r, g, b, alpha) +end + +-- Main placement function - now uses proper promise pattern +function PlaceableObject.Create(model, settings) + if isPlacing then + return nil -- Already placing + end + + settings = settings or {} + + -- Default settings + local config = { + depthMin = settings.depthMin or 2.0, + depthMax = settings.depthMax or 10.0, + rotationStep = settings.rotationStep or 15.0, + depthStep = settings.depthStep or 1.0, + heightStep = settings.heightStep or 0.1, -- New height step setting + disableSphere = settings.useSphere and false or true, + depth = settings.depth or 10.0, + allowMovement = settings.allowMovement ~= false, -- default true + allowNormal = settings.allowNormal ~= false, -- default true + allowVertical = settings.allowVertical ~= false, -- default true - allow vertical movement in normal mode + startMode = settings.startMode or 'normal', -- 'normal' or 'movement' + allowedMats = settings.allowedMats, + boundary = settings.boundary, + config = settings.config or {}, + maxDepth = settings.maxDepth or 10, + showInstructionalButtons = settings.showInstructionalButtons + } + + -- Create the promise and store it globally + currentPromise = promise.new() + + isPlacing = true + currentMode = config.startMode + + -- Create entity if model provided + if model then + local heading = -GetEntityHeading(PlayerPedId()) + local pos = eyetrace(config.depth, config.disableSphere) + local obj = Utility.CreateProp(model, pos, vector3(0, 0, heading), nil) + currentEntity = obj + else + currentEntity = settings.entity + end + + if not currentEntity then + isPlacing = false + if currentPromise then + currentPromise:resolve(nil) + currentPromise = nil + end + return nil + end + + -- Setup entity + SetEntityCollision(currentEntity, false, false) + SetEntityAlpha(currentEntity, 150, false) + SetPedConfigFlag(PlayerPedId(), 146, true) + SetCanClimbOnEntity(currentEntity, false) + SetEntityCompletelyDisableCollision(currentEntity, true, false) + SetEntityNoCollisionEntity(PlayerPedId(), currentEntity, false) + + -- Setup boundary checking + local getBoundsStatus = checkBoundaryAndMaterials(currentEntity, config) + + -- Setup instructional buttons only if enabled + local scaleform = nil + if config.showInstructionalButtons then + scaleform = setupInstructionalButtons(config) + end + + -- Main loop + CreateThread(function() + local lastMode = currentMode + while isPlacing do + -- Update instructional buttons if mode changed and buttons are enabled + if config.showInstructionalButtons and (not lastMode or lastMode ~= currentMode) then + scaleform = setupInstructionalButtons(config) + lastMode = currentMode + end + + -- Draw instructional buttons only if enabled + if config.showInstructionalButtons and scaleform then + DrawScaleformMovieFullscreen(scaleform, 255, 255, 255, 255, 0) + end + + -- Draw boundary box if defined + if config.boundary then + drawBoundaryBox(config.boundary) + end + + if currentMode == 'normal' and config.allowNormal then + normalPlacementLoop(currentEntity, config, getBoundsStatus) + elseif currentMode == 'movement' and config.allowMovement then + movementPlacementLoop(currentEntity, config, getBoundsStatus) + end + + Wait(0) + end + + -- Cleanup + if DoesEntityExist(currentEntity) then + if IsEntityAPed(currentEntity) then + SetEntityAlpha(currentEntity, 255) + end + SetEntityDrawOutline(currentEntity, false) + end + + currentEntity = nil + end) + + -- Return Citizen.Await on the promise + return Citizen.Await(currentPromise) +end + +-- Stop placement function +function PlaceableObject.Stop() + if not isPlacing then return false end + + isPlacing = false + if currentEntity and DoesEntityExist(currentEntity) then + DeleteEntity(currentEntity) + end + + return true +end + +-- Get current status +function PlaceableObject.IsPlacing() + return isPlacing +end + +function PlaceableObject.GetCurrentEntity() + return currentEntity +end + +function PlaceableObject.GetCurrentMode() + return currentMode +end + + + return PlaceableObject \ No newline at end of file diff --git a/lib/raycast/client/raycast.lua b/lib/raycast/client/raycast.lua index f067f6e..735db9f 100644 --- a/lib/raycast/client/raycast.lua +++ b/lib/raycast/client/raycast.lua @@ -35,7 +35,7 @@ function Raycast.ToCoords(startCoords, endCoords, flag, ignore) timeout = timeout - 1 Wait(0) end - return retval, entity, finalCoords, normals, material + return retval, entity, finalCoords, normals, material end function Raycast.FromCamera(flags, ignore, distance) @@ -44,9 +44,8 @@ function Raycast.FromCamera(flags, ignore, distance) local destination = coords + Raycast.GetForwardVector() * distance local retval, entity, finalCoords, normals, material = Raycast.ToCoords(coords, destination, flags, ignore) if retval ~= 1 then - print("Raycast hit max distance, trying again", coords, dist) local newDest = destination - vector3(0, 0, 10) - return Raycast.ToCoords(destination, newDest, flags, ignore) + return Raycast.ToCoords(destination, newDest, flags, ignore) end return retval, entity, finalCoords, normals, material end diff --git a/lib/shells/client/config.lua b/lib/shells/client/config.lua new file mode 100644 index 0000000..c259a1b --- /dev/null +++ b/lib/shells/client/config.lua @@ -0,0 +1,53 @@ +Shells = Shells or {} + + +--Data table +Shells.Targets = Shells.Targets or { + ['entrance'] = { + ['enter'] = { + label = 'Enter', + icon = 'fa-solid fa-door-open', + onSelect = function(entity, shellId, objectId) + TriggerServerEvent('community_bridge:server:EnterShell', shellId, objectId) + end + }, + }, + ['exit'] = { + ['leave'] = { + label = 'Exit', + icon = 'fa-solid fa-door-closed', + onSelect = function(entity, shellId, objectId) + TriggerServerEvent('community_bridge:server:ExitShell', shellId, objectId) + end + } + } +} + +--Functions to set data table +Shells.Target = { + Set = function(shellType, options) + assert(shellType, "Shells.Target.Set: 'shellType' is required") + options = options or {} + for key, value in pairs(options) do + if Shells.Targets[shellType] and Shells.Targets[shellType][key] then + value.onSelect = Shells.Targets[shellType][key].onSelect + end + Shells.Targets[shellType] = Shells.Targets[shellType] or {} + Shells.Targets[shellType][key] = value + end + return true + end, + Get = function(shellType, shellId, objectId) + local aOptions = {} + for key, value in pairs(Shells.Targets[shellType] or {}) do + local onSelect = value.onSelect + value.onSelect = function(entity) + onSelect(entity, shellId, objectId) + end + table.insert(aOptions, value) + end + return aOptions + end +} + +return Shells \ No newline at end of file diff --git a/lib/shells/client/shells.lua b/lib/shells/client/shells.lua new file mode 100644 index 0000000..2022c4f --- /dev/null +++ b/lib/shells/client/shells.lua @@ -0,0 +1,269 @@ +local Target = Require('modules/target/_default/init.lua') +local ClientEntity = Require("lib/entities/client/client_entity.lua") + + +Shells = Shells or Require("lib/shells/client/config.lua") +Shells.All = Shells.All or {} +local insideShell = false +Shells.Events = { + OnSpawn = {}, + OnRemove = {}, +} + +--Set Target lang or additionals +-- Shells.Target.Set('entrance', { +-- enter = { +-- label = 'yerp', +-- icon = 'fa-solid fa-door-open', +-- }, +-- }) + +-- Shells.Target.Set('exit', { +-- leave = { +-- label = 'leerp', +-- icon = 'fa-solid fa-door-closed', +-- }, +-- }) + +Shells.Event = { + Add = function(eventName, callback) + if Shells.Events[eventName] then + table.insert(Shells.Events[eventName], callback) + else + print(string.format("Shells.Event.Add: Invalid event name '%s'", eventName)) + end + end, + Trigger = function(eventName, ...) + if Shells.Events[eventName] then + for _, callback in ipairs(Shells.Events[eventName]) do + callback(...) + end + else + print(string.format("Shells.Event.Trigger: Invalid event name '%s'", eventName)) + end + end, +} + +-- Shells.Event.Add('OnSpawn', function(pointData, entity) +-- print(string.format("Exterior point created with ID: %s, Type: %s, Entity: %s", pointData.id, pointData.type, entity)) +-- end) +-- Shells.Event.Add('OnRemove', function(pointData) +-- print(string.format("Interior point created with ID: %s, Type: %s", pointData.id, pointData.type)) +-- end) + +function Shells.AddInteriorObject(shell, objectData) + objectData.OnSpawn = function(pointData) + Shells.Event.Trigger('OnSpawn', objectData, pointData.spawned) + local targetOptions = Shells.Target.Get(objectData.type, shell.id, objectData.id) + if targetOptions then + local size = vector3(objectData.distance / 2, objectData.distance / 2, objectData.distance / 2) -- this might need to be size + Target.AddBoxZone(objectData.id, objectData.coords, size, objectData.rotation.z, targetOptions, true) + end + end + objectData.OnRemove = function(pointData) + Shells.Event.Trigger('OnRemove', objectData, pointData.spawned) + Target.RemoveZone(objectData.id) + end + return ClientEntity.Register(objectData) +end + +function Shells.SetupInterior(shell) + if not shell or not shell.interior then return end + for _, v in pairs(shell.interior) do + local pointData = Shells.AddInteriorObject(shell, v) + shell.interiorSpawned[pointData.id] = pointData + end +end + +function Shells.SetupExterior(shell) + if not shell or not shell.exterior then return end + for k, v in pairs(shell.exterior) do + local pointData = Shells.AddInteriorObject(shell, v) + shell.exteriorSpawned[pointData.id] = pointData + end +end + +function Shells.ClearInterior(shell) + if not shell or not shell.interiorSpawned then return end + for _, v in pairs(shell.interiorSpawned) do + ClientEntity.Unregister(v.id) + Target.RemoveZone(v.id) + end + shell.interiorSpawned = {} +end + +function Shells.ClearExterior(shell) + if not shell or not shell.exteriorSpawned then return end + for _, v in pairs(shell.exteriorSpawned) do + ClientEntity.Unregister(v.id) + Target.RemoveZone(v.id) + end + shell.exteriorSpawned = {} +end + + +function Shells.New(data) + assert(data.id, "Shells.Create: 'id' is required") + assert(data.model, "Shells.Create: 'shellModel' is required") + assert(data.coords, "Shells.Create: 'coords' is required") + local exterior = data.exterior or {} + local exteriorSpawned = {} + for k, v in pairs(exterior or {}) do + v.OnSpawn = function(pointData) + Shells.Event.Trigger('OnSpawn', v, pointData.spawned) + local targetOptions = Shells.Target.Get(v.type, data.id, v.id) + if targetOptions then + local size = vector3(v.distance / 2, v.distance / 2, v.distance / 2) + Target.AddBoxZone(v.id, v.coords, size, v.rotation.z, targetOptions, true) + end + end + v.OnRemove = function(pointData) + Shells.Event.Trigger('OnRemove', v, pointData.spawned) + Target.RemoveZone(v.id) + end + local pointData = ClientEntity.Register(v) + exteriorSpawned[pointData.id] = pointData + end + data.interiorSpawned = {} + data.exteriorSpawned = exteriorSpawned + Shells.All[data.id] = data + return data +end + +local returnPoint = nil +function Shells.Enter(id, entranceId) + local shell = Shells.All[id] + if not shell then + print(string.format("Shells.Spawn: Shell with ID '%s' not found", id)) + return + end + local entrance = shell.interior[entranceId] + if not entrance then + print(string.format("Shells.Enter: Entrance with ID '%s' not found in shell '%s'", entranceId, id)) + return + end + local ped = PlayerPedId() + returnPoint = GetEntityCoords(ped) + DoScreenFadeOut(1000) + Wait(1000) + local entranceCoords = entrance.coords + SetEntityCoords(ped, entranceCoords.x, entranceCoords.y, entranceCoords.z, false, false, false, true) + FreezeEntityPosition(ped, true) + local oldShell = insideShell and Shells.All[insideShell] + if oldShell?.id ~= id then + Shells.ClearExterior(oldShell) + Shells.ClearInterior(oldShell) + end + Shells.ClearExterior(shell) + Shells.SetupInterior(shell) + ClientEntity.Register(shell) + Wait(1000) -- Wait for the fade out to complete + FreezeEntityPosition(ped, false) + DoScreenFadeIn(1000) + insideShell = shell.id +end + +function Shells.Exit(id, exitId) + local shell = Shells.All[id] + if not shell then + print(string.format("Shells.Exit: Shell with ID '%s' not found", id)) + return + end + local oldCoords = GetEntityCoords(PlayerPedId()) + local oldPoint = shell.exterior[exitId] + if not oldPoint then + print(string.format("Shells.Exit: Old point with ID '%s' not found in shell '%s'", exitId, id)) + return + end + DoScreenFadeOut(1000) + Wait(1000) + SetEntityCoords(PlayerPedId(), oldPoint.coords.x, oldPoint.coords.y, oldPoint.coords.z, false, false, false, true) + FreezeEntityPosition(PlayerPedId(), true) + Shells.ClearInterior(shell) + ClientEntity.Unregister(shell.id) + Shells.SetupExterior(shell) + shell.interiorSpawned = {} + FreezeEntityPosition(PlayerPedId(), false) + DoScreenFadeIn(1000) + insideShell = false +end + +function Shells.Inside() + return insideShell +end + +RegisterNetEvent('community_bridge:client:CreateShell', function(shell) + Shells.New(shell) +end) + +RegisterNetEvent('community_bridge:client:EnterShell', function(shellId, entranceId, oldId) + local shell = Shells.All[shellId] + if not shell then + print(string.format("Shells.EnterShell: Shell with ID '%s' not found", shellId)) + return + end + + Shells.Enter(shellId, entranceId, oldId) +end) + +RegisterNetEvent('community_bridge:client:ExitShell', function(shellId, oldId) + local shell = Shells.All[shellId] + print(string.format("Shells.ExitShell: Exiting shell '%s'", shellId)) + if not shell then + print(string.format("Shells.ExitShell: Shell with ID '%s' not found", shellId)) + return + end + Shells.Exit(shellId, oldId) + +end) + +RegisterNetEvent('community_bridge:client:AddObjectsToShell', function (shellId, interiorObjects, exteriorObjects) + local shell = Shells.All[shellId] + print(string.format("Shells.AddObjectsToShell: Adding objects to shell '%s'", shellId), + json.encode({interiorObjects = interiorObjects, exteriorObjects = exteriorObjects}, { indent = true })) + if not shell then + print(string.format("Shells.AddObjectsToShell: Shell with ID '%s' not found", shellId)) + return + end + local insideShell = Shells.Inside() + if interiorObjects then + for _, obj in pairs(interiorObjects) do + if not shell.interior[obj.id] then + shell.interior[obj.id] = obj + if insideShell and insideShell == shellId then + local pointData = Shells.AddInteriorObject(shell, obj) + shell.interiorSpawned[pointData.id] = pointData + end + end + end + end + if exteriorObjects then + for _, obj in pairs(exteriorObjects) do + if not shell.exterior[obj.id] then + shell.exterior[obj.id] = obj + if not insideShell then + local pointData = Shells.AddInteriorObject(shell, obj) + shell.exteriorSpawned[pointData.id] = pointData + end + end + end + end +end) + +RegisterNetEvent('community_bridge:client:CreateShells', function(shells) + print("Shells.CreateShells: Creating shells") + for _, shell in pairs(shells) do + Shells.New(shell) + end +end) +-- TriggerClientEvent('community_bridge:client:CreateShells', -1, toClient) +-- TriggerClientEvent('community_bridge:client:ExitShell', src, oldId) + + +AddEventHandler('onResourceStart', function(resource) + if resource == GetCurrentResourceName() then + DoScreenFadeIn(1000) -- Fade in when resource stops + if not returnPoint then return end + SetEntityCoords(PlayerPedId(), returnPoint.x, returnPoint.y, returnPoint.z, false, false, false, true) + end +end) \ No newline at end of file diff --git a/lib/shells/server/shells.lua b/lib/shells/server/shells.lua new file mode 100644 index 0000000..349c5ab --- /dev/null +++ b/lib/shells/server/shells.lua @@ -0,0 +1,379 @@ +Ids = Ids or Require("lib/utility/shared/ids.lua") +Shells = Shells or {} +Shells.All = Shells.All or {} +Shells.ActivePlayers = Shells.ActivePlayers or {} -- Track players in shells + +Shells.Interactable = Shells.Interactable or {} +Shells.BucketsInUse = Shells.BucketsInUse or {} -- Track buckets in use + +function Shells.Interactable.New(_type, id, model, coords, rotation, entityType, distance, meta) + assert(_type, "Shells.Interactable.Create: 'type' is required") + assert(id, "Shells.Interactable.Create: 'name' is required") + assert(coords, "Shells.Interactable.Create: 'coords' is required") + return { + type = _type, + id = id, + model = model, + coords = coords, + rotation = rotation or vector3(0.0, 0.0, 0.0), + distance = distance or 2.0, + entityType = entityType or "object", -- Default entity type + meta = meta or {}, + } +end + +function Shells.New(data) + local id = data.id or Ids.CreateUniqueId(Shells.All) + local _type = data.type or "none" + local model = data.model + local size = data.size or vector3(10.0, 10.0, 10.0) -- Default size if not provided + local coords = data.coords or vector3(0.0, 0.0, 0.0) -- Default coordinates if not provided + local rotation = data.rotation or vector3(0.0, 0.0, 0.0) -- Default rotation if not provided + local interior = data.interior or {} + local exterior = data.exterior or {} + local bucket = data.bucket or Ids.RandomNumber(Shells.BucketsInUse, 4) + assert(id, "Shells.Create: 'id' is required") + assert(model, "Shells.Create: 'shellModel' is required") + assert(coords, "Shells.Create: 'coords' is required") + + local interiorInteractions = {} + for k, v in pairs(interior or {}) do + local interiorCoords = coords + (v.offset or vector3(0.0, 0.0, 0.0)) + local interaction = Shells.Interactable.New( + v.type or "none", + v.id or Ids.CreateUniqueId(interiorInteractions), + v.model, + interiorCoords, + v.rotation or vector3(0.0, 0.0, 0.0), + v.entityType or "object", -- Default entity type for interior interactions + v.distance or 2.0, + v.meta + ) + interiorInteractions[interaction.id] = interaction + end + + local exteriorInteractions = {} + for k, v in pairs(exterior or {}) do + local interaction = Shells.Interactable.New( + v.type or "none", + v.id or Ids.CreateUniqueId(exteriorInteractions), + v.model, + v.coords, + v.rotation or vector3(0.0, 0.0, 0.0), + v.entityType or "object", -- Default entity type for exterior interactions + v.distance or 2.0, + v.meta + ) + exteriorInteractions[interaction.id] = interaction + end + + local shellData = { + id = id, + type = _type, + entityType = "object", -- Default entity type for shells + model = model, + coords = coords, + size = size or vector3(10.0, 10.0, 10.0), -- Default size if not provided + rotation = rotation or vector3(0.0, 0.0, 0.0), + interior = interiorInteractions, + exterior = exteriorInteractions, + } + + Shells.All[id] = shellData + return shellData +end + +function Shells.Create(data) + local shell = Shells.New(data) + assert(shell, "Shells.Create: 'shell' is required") + TriggerClientEvent('community_bridge:client:CreateShell', -1, shell) + return shell +end + +function Shells.CreateBulk(shells) + assert(shells, "Shells.CreateBulk: 'shells' is required") + assert(type(shells) == "table", "Shells.CreateBulk: 'shells' must be a table") + local toClient = {} + for _, shellData in pairs(shells) do + local shell = Shells.New(shellData) + toClient[shell.id] = shell + end + TriggerClientEvent('community_bridge:client:CreateShells', -1, toClient) +end + +function Shells.Enter(src, shellId, entranceId) + src = tonumber(src) + assert(src, "Shells.EnterShell: 'src' is required") + assert(shellId, "Shells.EnterShell: 'shellId' is required") + print(shellId) + local shell = Shells.All[shellId] + assert(shell, "Shell not found: " .. tostring(shellId)) + if shell.onEnter then + local canEnter = shell.onEnter(src, shellId) + if not canEnter then return false end + end + if not shell.bucket then + local randNum = Ids.RandomNumber(Shells.BucketsInUse, 4) + shell.bucket = tonumber(randNum) + Shells.BucketsInUse[tostring(randNum)] = true + end + print(shell.bucket) + SetPlayerRoutingBucket(src, shell.bucket) + local exit = shell.exterior[entranceId]?.meta?.link + TriggerClientEvent('community_bridge:client:EnterShell', src, shellId, exit, Shells.ActivePlayers[tostring(src)]) + Shells.ActivePlayers[tostring(src)] = shellId + return true +end + + +function Shells.Exit(src, shellId, oldId) + + print(oldId) + src = tonumber(src) + assert(src, "Shells.ExitShell: 'src' is required") + assert(shellId, "Player is not in a shell") + + local shell = Shells.All[shellId] + assert(shell, "Shell not found: " .. tostring(shellId)) + + -- Restore original routing bucket + SetPlayerRoutingBucket(src, 0) + local exit = shell.interior[oldId]?.meta?.link + -- Clear player's shell data + Shells.ActivePlayers[tostring(src)] = nil + if shell.onExit then + shell.onExit(src, shellId) + end + TriggerClientEvent('community_bridge:client:ExitShell', src, shellId, exit) + return true +end + + +function Shells.Get(shellId) + assert(shellId, "Shells.GetShellById: 'shellId' is required") + return Shells.All[shellId] +end + +function Shells.Inside(src) + src = tonumber(src) + assert(src, "Shells.IsInside: 'src' is required") + + local shellId = Shells.ActivePlayers[tostring(src)] + if not shellId then + return false + end + + local shell = Shells.All[shellId] + if not shell then + return false + end + + return shell +end + +function Shells.AddObjects(shellId, objects) + assert(shellId, "Shells.AddObjects: 'shellId' is required") + assert(objects, "Shells.AddObjects: 'objects' is required") + assert(type(objects) == "table", "Shells.AddObjects: 'objects' must be a table") + + local shell = Shells.All[shellId] + assert(shell, "Shell not found: " .. tostring(shellId)) + + local interiors = objects.interior or {} + local exteriors = objects.exterior or {} + for _, objData in pairs(interiors) do + local obj = Shells.Interactable.New( + objData.type, + objData.id, + objData.model, + objData.coords, + objData.rotation, + objData.entityType, + objData.distance, + objData.meta + ) + shell.interior[obj.id] = obj -- Update the shell's interior with the new object + end + for _, objData in pairs(exteriors) do + local obj = Shells.Interactable.New( + objData.type, + objData.id, + objData.model, + objData.coords, + objData.rotation, + objData.entityType, + objData.distance, + objData.meta + ) + shell.exterior[obj.id] = obj -- Update the shell's exterior with the new object + end + + TriggerClientEvent('community_bridge:client:AddObjectsToShell', -1, shellId, shell.interior, shell.exterior) + return shell +end + +function Shells.RemoveObjects(shellId, objectIds) + assert(shellId, "Shells.RemoveObjects: 'shellId' is required") + assert(objectIds, "Shells.RemoveObjects: 'objects' is required") + if type(objectIds) ~= "table" then + objectIds = {objectIds} -- Ensure it's a table + end + + local shell = Shells.All[shellId] + assert(shell, "Shell not found: " .. tostring(shellId)) + + for _, objId in pairs(objectIds) do + shell.interior[objId] = nil + shell.exterior[objId] = nil + end + + TriggerClientEvent('community_bridge:client:RemoveObjectsFromShell', -1, shellId, objectIds) + return shell +end + +RegisterNetEvent('community_bridge:server:EnterShell', function(shellId, entranceId) + local src = source + Shells.Enter(src, shellId, entranceId) +end) + +RegisterNetEvent('community_bridge:server:ExitShell', function(shellId, oldId) + local src = source + Shells.Exit(src, shellId, oldId) +end) + +AddEventHandler('onPlayerJoining', function(playerId) + local src = source + TriggerClientEvent('community_bridge:client:CreateShells', src, Shells.All) +end) + +function Shells.GetInteractable(shellId, id) + assert(shellId, "Shells.GetInteractable: 'shellId' is required") + assert(id, "Shells.GetInteractable: 'id' is required") + + local shell = Shells.All[shellId] + if not shell then + return nil, "Shell not found: " .. tostring(shellId) + end + + local interactable = shell.interior[id] or shell.exterior[id] + if not interactable then + return nil, "Interactable not found: " .. tostring(id) + end + + return interactable +end + +function Shells.GetClosestInteractable(shellId, coords, exterior) + assert(shellId, "Shells.GetClosestInteriorInteractable: 'shellId' is required") + assert(coords, "Shells.GetClosestInteriorInteractable: 'coords' is required") + + local shell = Shells.All[shellId] + if not shell then + return nil, "Shell not found: " .. tostring(shellId) + end + + local closest = nil + local closestDistance = math.huge + if exterior then + for _, interactable in pairs(shell.exterior) do + local distance = #(coords - interactable.coords) + if distance < closestDistance then + closestDistance = distance + closest = interactable + end + end + return closest, closestDistance + end + + for _, interactable in pairs(shell.interior) do + local distance = #(coords - interactable.coords) + if distance < closestDistance then + closestDistance = distance + closest = interactable + end + end + return closest, closestDistance +end + +local testShell = nil +RegisterCommand('shells:create', function(source, args, rawCommand) + local coords = GetEntityCoords(GetPlayerPed(source)) + if testShell then + Shells.Exit(source, testShell.id, 'exit1') -- Exit previous shell if it exists + end + testShell = Shells.Create({ + id = Ids.CreateUniqueId(Shells.All), + type = "shell", + model = "shell_garagem", + coords = coords + vector3(0.0, 0.0, 100.0), -- Adjusted to place shell slightly below player + rotation = vector3(0.0, 0.0, 0.0), + size = vector3(10.0, 10.0, 10.0), + interior = { + { + id = 'exit1', + type = 'exit', + coords = coords + vector3(0.0, 0.0, 1.0), + rotation = vector3(0.0, 0.0, 0.0), + distance = 2.0, + meta = { + link = 'entrance1', + } + } + }, + exterior = { + { + id = 'entrance1', + type = 'entrance', + -- entityType = "object", + -- model = "xm_int_lev_sub_chair_02", + coords = coords - vector3(0.0, 0.0, 0.5), + rotation = vector3(0.0, 0.0, 0.0), + distance = 2.0, + meta = { + link = 'exit1', + } + } + }, + }) +end, true) + +RegisterCommand('shells:addobject', function(source, args, rawCommand) + if not testShell then + print("No shell created. Use /shells:create first.") + return + end + local model = args[1] + if not model then + print("Usage: /shells:addobject ") + return + end + + local shellId = testShell.id + local coords = GetEntityCoords(GetPlayerPed(source)) + local objectData = { + type = "none", + entityType = "ped", + id = Ids.CreateUniqueId(Shells.All[shellId].interior), + model = model, + coords = coords - vector3(0.0, 0.0, 0.5), -- Adjusted to place object slightly above player + rotation = vector3(0.0, 0.0, 0.0), + distance = 2.0, + meta = {} + } + Shells.AddObjects(shellId, {interior = {objectData}}) +end, true) + +AddEventHandler('onResourceStop', function(resource) + if resource == GetCurrentResourceName() then + for src, shellId in pairs(Shells.ActivePlayers) do + SetPlayerRoutingBucket(tonumber(src), 0) -- Reset routing bucket for all players + end + end +end) + +AddEventHandler('community_bridge:Server:OnPlayerUnload', function(src) + if not Shells.ActivePlayers[tostring(src)] then return end + print(string.format("Player %d is exiting shell %s", src, Shells.ActivePlayers[tostring(src)])) + Shells.Exit(src, Shells.ActivePlayers[tostring(src)]) + Shells.ActivePlayers[tostring(src)] = nil +end) \ No newline at end of file diff --git a/lib/utility/client/utility.lua b/lib/utility/client/utility.lua index 3f410c3..c35bf65 100644 --- a/lib/utility/client/utility.lua +++ b/lib/utility/client/utility.lua @@ -3,6 +3,8 @@ Utility = Utility or {} local blipIDs = {} local spawnedPeds = {} +Locales = Locales or Require('modules/locales/shared.lua') + -- === Local Helpers === ---Get the hash of a model (string or number) @@ -61,6 +63,30 @@ local function safeAddBlip(coords, sprite, color, scale, label, shortRange, disp return blip end +---Create a entiyty blip safely and store its reference +---@param entity number +---@param sprite number +---@param color number +---@param scale number +---@param label string +---@param shortRange boolean +---@param displayType number +---@return number +local function safeAddEntityBlip(entity, sprite, color, scale, label, shortRange, displayType) + local blip = AddBlipForEntity(entity) + SetBlipSprite(blip, sprite or 8) + SetBlipColour(blip, color or 3) + SetBlipScale(blip, scale or 0.8) + SetBlipDisplay(blip, displayType or 2) + SetBlipAsShortRange(blip, shortRange) + ShowHeadingIndicatorOnBlip(blip, true) + addTextEntryOnce(label, label) + BeginTextCommandSetBlipName(label) + EndTextCommandSetBlipName(blip) + table.insert(blipIDs, blip) + return blip +end + ---Remove a blip safely from the stored list ---@param blip number ---@return boolean @@ -178,6 +204,19 @@ function Utility.CreateBlip(coords, sprite, color, scale, label, shortRange, dis return safeAddBlip(coords, sprite, color, scale, label, shortRange, displayType) end +---Create a blip on the provided entity +---@param entity number +---@param sprite number +---@param color number +---@param scale number +---@param label string +---@param shortRange boolean +---@param displayType number +---@return number +function Utility.CreateEntityBlip(entity, sprite, color, scale, label, shortRange, displayType) + return safeAddEntityBlip(entity, sprite, color, scale, label, shortRange, displayType) +end + ---Remove a blip if it exists ---@param blip number ---@return boolean @@ -387,6 +426,39 @@ function Utility.GetClosestPlayer(coords, distanceScope, includeMe) return closestPlayer, closestDistance, GetPlayerServerId(closestPlayer) end +---Get the closest vehicle to given coordinates +---@param coords vector3|nil +---@param distanceScope number|nil +---@param includePlayerVeh boolean|nil +---@return number|nil, vector3|nil, number|nil +function Utility.GetClosestVehicle(coords, distanceScope, includePlayerVeh) + local vehicleEntity = nil + local vehicleNetID = nil + local vehicleCoords = nil + local selfCoords = coords or GetEntityCoords(cache.ped) + local closestDistance = distanceScope or 5 + local includeMyVeh = includePlayerVeh or false + local gamePoolVehicles = GetGamePool("CVehicle") + + local playerVehicle = IsPedInAnyVehicle(cache.ped, false) and GetVehiclePedIsIn(cache.ped, false) or 0 + + for i = 1, #gamePoolVehicles do + local thisVehicle = gamePoolVehicles[i] + if DoesEntityExist(thisVehicle) and (includeMyVeh or thisVehicle ~= playerVehicle) then + local thisVehicleCoords = GetEntityCoords(thisVehicle) + local distance = #(selfCoords - thisVehicleCoords) + if closestDistance == -1 or distance < closestDistance then + vehicleEntity = thisVehicle + vehicleNetID = NetworkGetNetworkIdFromEntity(thisVehicle) or nil + vehicleCoords = thisVehicleCoords + closestDistance = distance + end + end + end + + return vehicleEntity, vehicleCoords, vehicleNetID +end + -- Deprecated point functions (no changes) function Utility.RegisterPoint(pointID, pointCoords, pointDistance, _onEnter, _onExit, _nearby) return Point.Register(pointID, pointCoords, pointDistance, nil, _onEnter, _onExit, _nearby) @@ -409,7 +481,7 @@ end ---@param value T The value to match against the cases ---@param cases table Table with case functions and an optional default (false key) ---@return any|false result The return value of the matched case function, or false if none matched -function Utility.Switch(value, cases) +function Utility.Switch(value, cases) local caseFunc = cases[value] or cases[false] if caseFunc and type(caseFunc) == "function" then @@ -420,31 +492,19 @@ function Utility.Switch(value, cases) return false end ---[[ -local vehicleType = "boat" - -local result = Utility.Switch(vehicleType, { - car = function() - print("This is a Car") - -- Car-related logic here - return "Car logic executed" - end, - bike = function() - print("This is a Bike") - -- Bike-related logic here - return "Bike logic executed" - end, - [false] = function() - print("Unknown vehicle type. Running default logic.") - -- Default logic here - return "Default logic executed" - end, -}) - -print("Result:", result) - -]] - +function Utility.CopyToClipboard(text) + if not text then return false end + if type(text) ~= "string" then + text = json.encode(text, { indent = true }) + end + SendNUIMessage({ + type = "copytoclipboard", + text = text + }) + local message = Locales and Locales.Locale("clipboard.copy") + --TriggerEvent('community_bridge:Client:Notify', message, 'success') + return true +end --- Pattern match-like function ---@generic T @@ -473,28 +533,13 @@ function Utility.Match(value, patterns) return false end ---[[ -local input = 42 - -local result = Utility.Match(input, { - [function(v) return v < 0 end] = function() - print("Negative number") - return "Negative" - end, - [function(v) return v % 2 == 0 end] = function() - print("Even number") - return "Even" - end, - [false] = function() - print("No match") - return "Default" - end, -}) - -print("Result:", result) - -]] - +---Get zone name at coordinates +---@param coords vector3 +---@return string +function Utility.GetZoneName(coords) + local zoneHash = GetNameOfZone(coords.x, coords.y, coords.z) + return GetLabelText(zoneHash) +end AddEventHandler('onResourceStop', function(resource) if resource ~= GetCurrentResourceName() then return end diff --git a/lib/utility/shared/cache.lua b/lib/utility/shared/cache.lua deleted file mode 100644 index e69de29..0000000 diff --git a/lib/utility/shared/tables.lua b/lib/utility/shared/tables.lua index 6feeb1a..1c6632c 100644 --- a/lib/utility/shared/tables.lua +++ b/lib/utility/shared/tables.lua @@ -115,5 +115,16 @@ Table.Shuffle = function(tbl) return tbl end +Table.Compare = function(a, b) + if type(a) == "table" then + for k, v in pairs(a) do + if not Table.Compare(v, b[k]) then return false end + end + return true + else + return a == b + end +end + exports("Table", Table) return Table \ No newline at end of file diff --git a/locales/af.json b/locales/af.json new file mode 100644 index 0000000..a173525 --- /dev/null +++ b/locales/af.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Jy het nie genoeg geld om hierdie item te koop nie", + "Input": "Hoeveelheid invoer", + "PurchaseAmount": "Aankoop hoeveelheid", + "PurchasedItem": "Jy het gekoop ", + "CurrencySymbol": "R", + "Confirm": "Bevestig aankoop", + "AreYouSure": "Is jy seker jy wil 'n ", + "PayByCash": "Betaal kontant", + "PayByCard": "Betaal met kaart" + }, + "UNITTEST": { + "UNITTESTA": "Ek is 'n %s %s", + "locale-unit-test": "Dit is 'n toets string" + }, + "clipboard": { + "copy": "Gekopieer na knipbord" + }, + "placeable_object": { + "no_prop_defined": "Jy het geen voorwerp gedefinieer om te plaas nie", + "cant_place_here": "Jy kan nie hierdie voorwerp hier plaas nie", + "place_object_place": "[E] Plaas \n", + "place_object_cancel": "[X] Kanselleer \n", + "place_object_scroll_up": "[SCROLL UP] Draai regs \n", + "place_object_scroll_down": "[SCROLL DOWN] Draai links" + } +} diff --git a/locales/ar.json b/locales/ar.json new file mode 100644 index 0000000..0f82346 --- /dev/null +++ b/locales/ar.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "ليس لديك مال كافٍ لشراء هذا العنصر", + "Input": "إدخال الكمية", + "PurchaseAmount": "كمية الشراء", + "PurchasedItem": "لقد اشتريت ", + "CurrencySymbol": "ر.س", + "Confirm": "تأكيد الشراء", + "AreYouSure": "هل أنت متأكد من أنك تريد شراء ", + "PayByCash": "الدفع نقداً", + "PayByCard": "الدفع بالبطاقة" + }, + "UNITTEST": { + "UNITTESTA": "أنا %s %s", + "locale-unit-test": "هذا نص تجريبي" + }, + "clipboard": { + "copy": "تم النسخ إلى الحافظة" + }, + "placeable_object": { + "no_prop_defined": "لم تحدد أي كائن للوضع", + "cant_place_here": "لا يمكنك وضع هذا الكائن هنا", + "place_object_place": "[E] وضع \n", + "place_object_cancel": "[X] إلغاء \n", + "place_object_scroll_up": "[SCROLL UP] تدوير يمين \n", + "place_object_scroll_down": "[SCROLL DOWN] تدوير يسار" + } +} diff --git a/locales/cs.json b/locales/cs.json new file mode 100644 index 0000000..45653d1 --- /dev/null +++ b/locales/cs.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Nemáte dostatek peněz na nákup této položky", + "Input": "Zadání množství", + "PurchaseAmount": "Množství k nákupu", + "PurchasedItem": "Zakoupili jste ", + "CurrencySymbol": "Kč", + "Confirm": "Potvrdit nákup", + "AreYouSure": "Jste si jisti, že chcete koupit ", + "PayByCash": "Platit hotově", + "PayByCard": "Platit kartou" + }, + "UNITTEST": { + "UNITTESTA": "Jsem %s %s", + "locale-unit-test": "Toto je testovací řetězec" + }, + "clipboard": { + "copy": "Zkopírováno do schránky" + }, + "placeable_object": { + "no_prop_defined": "Nedefinovali jste žádný objekt k umístění", + "cant_place_here": "Tento objekt zde nemůžete umístit", + "place_object_place": "[E] Umístit \n", + "place_object_cancel": "[X] Zrušit \n", + "place_object_scroll_up": "[SCROLL UP] Otočit doprava \n", + "place_object_scroll_down": "[SCROLL DOWN] Otočit doleva" + } +} diff --git a/locales/da.json b/locales/da.json new file mode 100644 index 0000000..d88f15a --- /dev/null +++ b/locales/da.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Du har ikke nok penge til at købe denne vare", + "Input": "Mængde input", + "PurchaseAmount": "Købsmængde", + "PurchasedItem": "Du har købt ", + "CurrencySymbol": "kr", + "Confirm": "Bekræft køb", + "AreYouSure": "Er du sikker på, at du vil købe en ", + "PayByCash": "Betal kontant", + "PayByCard": "Betal med kort" + }, + "UNITTEST": { + "UNITTESTA": "Jeg er en %s %s", + "locale-unit-test": "Dette er en test streng" + }, + "clipboard": { + "copy": "Kopieret til udklipsholder" + }, + "placeable_object": { + "no_prop_defined": "Du har ikke defineret noget objekt at placere", + "cant_place_here": "Du kan ikke placere dette objekt her", + "place_object_place": "[E] Placer \n", + "place_object_cancel": "[X] Annuller \n", + "place_object_scroll_up": "[SCROLL UP] Drej til højre \n", + "place_object_scroll_down": "[SCROLL DOWN] Drej til venstre" + } +} diff --git a/locales/de.json b/locales/de.json new file mode 100644 index 0000000..d146bcb --- /dev/null +++ b/locales/de.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Du hast nicht genug Geld, um diesen Artikel zu kaufen", + "Input": "Mengeneingabe", + "PurchaseAmount": "Kaufmenge", + "PurchasedItem": "Du hast gekauft ", + "CurrencySymbol": "€", + "Confirm": "Kauf bestätigen", + "AreYouSure": "Bist du sicher, dass du einen ", + "PayByCash": "Bar bezahlen", + "PayByCard": "Mit Karte bezahlen" + }, + "UNITTEST": { + "UNITTESTA": "Ich bin ein %s %s", + "locale-unit-test": "Das ist ein Teststring" + }, + "clipboard": { + "copy": "In die Zwischenablage kopiert" + }, + "placeable_object": { + "no_prop_defined": "Du hast kein Objekt zum Platzieren definiert", + "cant_place_here": "Du kannst dieses Objekt hier nicht platzieren", + "place_object_place": "[E] Platzieren \n", + "place_object_cancel": "[X] Abbrechen \n", + "place_object_scroll_up": "[SCROLL UP] Rechts drehen \n", + "place_object_scroll_down": "[SCROLL DOWN] Links drehen" + } +} diff --git a/locales/el.json b/locales/el.json new file mode 100644 index 0000000..3efe343 --- /dev/null +++ b/locales/el.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Δεν έχετε αρκετά χρήματα για να αγοράσετε αυτό το αντικείμενο", + "Input": "Εισαγωγή ποσότητας", + "PurchaseAmount": "Ποσότητα αγοράς", + "PurchasedItem": "Αγοράσατε ", + "CurrencySymbol": "€", + "Confirm": "Επιβεβαίωση αγοράς", + "AreYouSure": "Είστε σίγουροι ότι θέλετε να αγοράσετε ", + "PayByCash": "Πληρωμή με μετρητά", + "PayByCard": "Πληρωμή με κάρτα" + }, + "UNITTEST": { + "UNITTESTA": "Είμαι ένας %s %s", + "locale-unit-test": "Αυτή είναι μια συμβολοσειρά δοκιμής" + }, + "clipboard": { + "copy": "Αντιγράφηκε στο πρόχειρο" + }, + "placeable_object": { + "no_prop_defined": "Δεν έχετε ορίσει κάποιο αντικείμενο προς τοποθέτηση", + "cant_place_here": "Δεν μπορείτε να τοποθετήσετε αυτό το αντικείμενο εδώ", + "place_object_place": "[E] Τοποθέτηση \n", + "place_object_cancel": "[X] Ακύρωση \n", + "place_object_scroll_up": "[SCROLL UP] Περιστροφή δεξιά \n", + "place_object_scroll_down": "[SCROLL DOWN] Περιστροφή αριστερά" + } +} diff --git a/locales/en.json b/locales/en.json index fef60d1..27726a4 100644 --- a/locales/en.json +++ b/locales/en.json @@ -1,45 +1,28 @@ { - "locale-unit-test": "This is a test string", - "place_object_place": "[E] Place \n", - "place_object_cancel": "[X] Cancel \n", - "place_object_scroll_up": "[SCROLL UP] Turn right \n", - "place_object_scroll_down": "[SCROLL DOWN] Turn left", - "enter_text": "Enter Text", - "no_prop_defined": "You didnt define any object to place", - "Shops": { - "NotEnoughMoney": "You dont have enough money to buy this item", - "Input": "Amount Input", - "PurchaseAmount": "Purchase Quanity", - "PurchasedItem": "You Have Purchased ", - "CurrencySymbol": "$", - "Confirm": "Confirm Purchase", - "AreYouSure": "Are you sure you want to purchase a ", - "PayByCash": "Pay by cash", - "PayByCard": "Pay by card" - }, - "UNITTEST": { - "UNITTESTA": "Im a %s %s", - "UNITTEST": { - "UNITTESTA": "\n.-._ _,-,\n`._`-._ _,-'_,'\n `._ `-._ _,-' _,'\n `._ `-._ __.-----.__ _,-' _,'\n `._ `#===\\\"\\\"\\\" \\\"\\\"\\\"===#' _,'\n `._/) ._ _. (\\_,'\n )*' **.__ __.** '*(\n # .==..__ \\\"\\\" \\\"\\\" __..==, #\n # `\\\"._(_). .(_)_.\\\"' #" - } - }, - "accessibility": { - "cb_command": "colourblindness", - "cb_title": "Colourblindness Options", - "cb_desc": "Select your type of colourblindness\nCurrent Colourblindness: %s", - "cb_none": "None", - "cb_updated": "Colourblindness has been updated to %s", - "cb_default_title": "No Colourblindness", - "cb_default_desc": "No colourblindness.\nThis is the default option.", - "cb_protanomaly_title": "Protanomaly", - "cb_protanomaly_desc": "Red-green color blindness.\nMakes certain shades of red look more green and less bright.\nThis type is mild and usually doesn’t get in the way of normal activities.", - "cb_deuteranomaly_title": "Deuteranomaly", - "cb_deuteranomaly_desc": "Red-green color blindness.\nIt makes certain shades of green look more red.\nThis type is mild and doesn’t usually get in the way of normal activities.", - "cb_dual_title": "Protanopia and Deuteranopia", - "cb_dual_desc": "Red-green color blindness.\nMakes someone unable to tell the difference between red and green at all.", - "cb_tritanopia_title": "Tritanopia", - "cb_tritanopia_desc": "Blue-yellow color blindness that makes someone unable to tell the difference between blue and green, purple and red, and yellow and pink.\nIt also makes colors look less bright.", - "cb_tritanomaly_title": "Tritanomaly", - "cb_tritanomaly_desc": "Blue-yellow color blindness makes it hard to tell the difference between blue and green and between yellow and red." - } -} + "Shops": { + "NotEnoughMoney": "You dont have enough money to buy this item", + "Input": "Amount Input", + "PurchaseAmount": "Purchase Quanity", + "PurchasedItem": "You Have Purchased ", + "CurrencySymbol": "$", + "Confirm": "Confirm Purchase", + "AreYouSure": "Are you sure you want to purchase a ", + "PayByCash": "Pay by cash", + "PayByCard": "Pay by card" + }, + "UNITTEST": { + "UNITTESTA": "Im a %s %s", + "locale-unit-test": "This is a test string" + }, + "clipboard": { + "copy": "Copied to clipboard" + }, + "placeable_object": { + "no_prop_defined": "You didnt define any object to place", + "cant_place_here": "You can't place this object here", + "place_object_place": "[E] Place \n", + "place_object_cancel": "[X] Cancel \n", + "place_object_scroll_up": "[SCROLL UP] Turn right \n", + "place_object_scroll_down": "[SCROLL DOWN] Turn left" + } +} \ No newline at end of file diff --git a/locales/es.json b/locales/es.json new file mode 100644 index 0000000..e029410 --- /dev/null +++ b/locales/es.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "No tienes suficiente dinero para comprar este artículo", + "Input": "Entrada de cantidad", + "PurchaseAmount": "Cantidad de compra", + "PurchasedItem": "Has comprado ", + "CurrencySymbol": "€", + "Confirm": "Confirmar compra", + "AreYouSure": "¿Estás seguro de que quieres comprar un ", + "PayByCash": "Pagar en efectivo", + "PayByCard": "Pagar con tarjeta" + }, + "UNITTEST": { + "UNITTESTA": "Soy un %s %s", + "locale-unit-test": "Esta es una cadena de prueba" + }, + "clipboard": { + "copy": "Copiado al portapapeles" + }, + "placeable_object": { + "no_prop_defined": "No has definido ningún objeto para colocar", + "cant_place_here": "No puedes colocar este objeto aquí", + "place_object_place": "[E] Colocar \n", + "place_object_cancel": "[X] Cancelar \n", + "place_object_scroll_up": "[SCROLL UP] Girar a la derecha \n", + "place_object_scroll_down": "[SCROLL DOWN] Girar a la izquierda" + } +} diff --git a/locales/fi.json b/locales/fi.json new file mode 100644 index 0000000..3c84e82 --- /dev/null +++ b/locales/fi.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Sinulla ei ole tarpeeksi rahaa tämän tuotteen ostamiseen", + "Input": "Määrän syöttö", + "PurchaseAmount": "Ostomäärä", + "PurchasedItem": "Ostit ", + "CurrencySymbol": "€", + "Confirm": "Vahvista osto", + "AreYouSure": "Oletko varma, että haluat ostaa ", + "PayByCash": "Maksa käteisellä", + "PayByCard": "Maksa kortilla" + }, + "UNITTEST": { + "UNITTESTA": "Olen %s %s", + "locale-unit-test": "Tämä on testijono" + }, + "clipboard": { + "copy": "Kopioitu leikepöydälle" + }, + "placeable_object": { + "no_prop_defined": "Et ole määritellyt mitään objektia sijoitettavaksi", + "cant_place_here": "Et voi sijoittaa tätä objektia tähän", + "place_object_place": "[E] Sijoita \n", + "place_object_cancel": "[X] Peruuta \n", + "place_object_scroll_up": "[SCROLL UP] Käännä oikealle \n", + "place_object_scroll_down": "[SCROLL DOWN] Käännä vasemmalle" + } +} diff --git a/locales/fr.json b/locales/fr.json new file mode 100644 index 0000000..83c3da9 --- /dev/null +++ b/locales/fr.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Vous n'avez pas assez d'argent pour acheter cet article", + "Input": "Saisie de quantité", + "PurchaseAmount": "Quantité d'achat", + "PurchasedItem": "Vous avez acheté ", + "CurrencySymbol": "€", + "Confirm": "Confirmer l'achat", + "AreYouSure": "Êtes-vous sûr de vouloir acheter un ", + "PayByCash": "Payer en espèces", + "PayByCard": "Payer par carte" + }, + "UNITTEST": { + "UNITTESTA": "Je suis un %s %s", + "locale-unit-test": "Ceci est une chaîne de test" + }, + "clipboard": { + "copy": "Copié dans le presse-papiers" + }, + "placeable_object": { + "no_prop_defined": "Vous n'avez défini aucun objet à placer", + "cant_place_here": "Vous ne pouvez pas placer cet objet ici", + "place_object_place": "[E] Placer \n", + "place_object_cancel": "[X] Annuler \n", + "place_object_scroll_up": "[SCROLL UP] Tourner à droite \n", + "place_object_scroll_down": "[SCROLL DOWN] Tourner à gauche" + } +} diff --git a/locales/hi.json b/locales/hi.json new file mode 100644 index 0000000..ca9de22 --- /dev/null +++ b/locales/hi.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "आपके पास इस वस्तु को खरीदने के लिए पर्याप्त पैसे नहीं हैं", + "Input": "मात्रा इनपुट", + "PurchaseAmount": "खरीदारी की मात्रा", + "PurchasedItem": "आपने खरीदा है ", + "CurrencySymbol": "₹", + "Confirm": "खरीदारी की पुष्टि करें", + "AreYouSure": "क्या आप वाकई एक खरीदना चाहते हैं ", + "PayByCash": "नकद भुगतान करें", + "PayByCard": "कार्ड से भुगतान करें" + }, + "UNITTEST": { + "UNITTESTA": "मैं एक %s %s हूँ", + "locale-unit-test": "यह एक परीक्षण स्ट्रिंग है" + }, + "clipboard": { + "copy": "क्लिपबोर्ड में कॉपी किया गया" + }, + "placeable_object": { + "no_prop_defined": "आपने रखने के लिए कोई वस्तु परिभाषित नहीं की है", + "cant_place_here": "आप इस वस्तु को यहाँ नहीं रख सकते", + "place_object_place": "[E] रखें \n", + "place_object_cancel": "[X] रद्द करें \n", + "place_object_scroll_up": "[SCROLL UP] दाईं ओर घुमाएं \n", + "place_object_scroll_down": "[SCROLL DOWN] बाईं ओर घुमाएं" + } +} diff --git a/locales/hu.json b/locales/hu.json new file mode 100644 index 0000000..5f1febf --- /dev/null +++ b/locales/hu.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Nincs elegendő pénzed ennek a tételnek a megvásárlásához", + "Input": "Mennyiség bevitel", + "PurchaseAmount": "Vásárlási mennyiség", + "PurchasedItem": "Megvásároltad ", + "CurrencySymbol": "Ft", + "Confirm": "Vásárlás megerősítése", + "AreYouSure": "Biztos vagy benne, hogy meg akarsz vásárolni ", + "PayByCash": "Készpénzzel fizet", + "PayByCard": "Kártyával fizet" + }, + "UNITTEST": { + "UNITTESTA": "Én egy %s %s vagyok", + "locale-unit-test": "Ez egy teszt karakterlánc" + }, + "clipboard": { + "copy": "Vágólapra másolva" + }, + "placeable_object": { + "no_prop_defined": "Nem definiáltál semmilyen objektumot elhelyezésre", + "cant_place_here": "Nem helyezheted el ezt az objektumot itt", + "place_object_place": "[E] Elhelyez \n", + "place_object_cancel": "[X] Mégse \n", + "place_object_scroll_up": "[SCROLL UP] Forgatás jobbra \n", + "place_object_scroll_down": "[SCROLL DOWN] Forgatás balra" + } +} diff --git a/locales/it.json b/locales/it.json new file mode 100644 index 0000000..5c77881 --- /dev/null +++ b/locales/it.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Non hai abbastanza soldi per comprare questo articolo", + "Input": "Inserimento quantità", + "PurchaseAmount": "Quantità di acquisto", + "PurchasedItem": "Hai acquistato ", + "CurrencySymbol": "€", + "Confirm": "Conferma acquisto", + "AreYouSure": "Sei sicuro di voler comprare un ", + "PayByCash": "Paga in contanti", + "PayByCard": "Paga con carta" + }, + "UNITTEST": { + "UNITTESTA": "Sono un %s %s", + "locale-unit-test": "Questa è una stringa di test" + }, + "clipboard": { + "copy": "Copiato negli appunti" + }, + "placeable_object": { + "no_prop_defined": "Non hai definito nessun oggetto da posizionare", + "cant_place_here": "Non puoi posizionare questo oggetto qui", + "place_object_place": "[E] Posiziona \n", + "place_object_cancel": "[X] Annulla \n", + "place_object_scroll_up": "[SCROLL UP] Ruota a destra \n", + "place_object_scroll_down": "[SCROLL DOWN] Ruota a sinistra" + } +} diff --git a/locales/ja.json b/locales/ja.json new file mode 100644 index 0000000..c1691e2 --- /dev/null +++ b/locales/ja.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "このアイテムを購入するのに十分なお金がありません", + "Input": "数量入力", + "PurchaseAmount": "購入数量", + "PurchasedItem": "購入しました ", + "CurrencySymbol": "¥", + "Confirm": "購入を確認", + "AreYouSure": "本当に購入しますか ", + "PayByCash": "現金で支払う", + "PayByCard": "カードで支払う" + }, + "UNITTEST": { + "UNITTESTA": "私は%s %sです", + "locale-unit-test": "これはテスト文字列です" + }, + "clipboard": { + "copy": "クリップボードにコピーしました" + }, + "placeable_object": { + "no_prop_defined": "配置するオブジェクトが定義されていません", + "cant_place_here": "ここにこのオブジェクトを配置できません", + "place_object_place": "[E] 配置 \n", + "place_object_cancel": "[X] キャンセル \n", + "place_object_scroll_up": "[SCROLL UP] 右回転 \n", + "place_object_scroll_down": "[SCROLL DOWN] 左回転" + } +} diff --git a/locales/ko.json b/locales/ko.json new file mode 100644 index 0000000..f62cce2 --- /dev/null +++ b/locales/ko.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "이 아이템을 구매할 돈이 부족합니다", + "Input": "수량 입력", + "PurchaseAmount": "구매 수량", + "PurchasedItem": "구매했습니다 ", + "CurrencySymbol": "₩", + "Confirm": "구매 확인", + "AreYouSure": "정말로 구매하시겠습니까 ", + "PayByCash": "현금으로 결제", + "PayByCard": "카드로 결제" + }, + "UNITTEST": { + "UNITTESTA": "나는 %s %s입니다", + "locale-unit-test": "이것은 테스트 문자열입니다" + }, + "clipboard": { + "copy": "클립보드에 복사됨" + }, + "placeable_object": { + "no_prop_defined": "배치할 객체를 정의하지 않았습니다", + "cant_place_here": "여기에 이 객체를 배치할 수 없습니다", + "place_object_place": "[E] 배치 \n", + "place_object_cancel": "[X] 취소 \n", + "place_object_scroll_up": "[SCROLL UP] 오른쪽으로 회전 \n", + "place_object_scroll_down": "[SCROLL DOWN] 왼쪽으로 회전" + } +} diff --git a/locales/nl.json b/locales/nl.json new file mode 100644 index 0000000..e1426bc --- /dev/null +++ b/locales/nl.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Je hebt niet genoeg geld om dit item te kopen", + "Input": "Hoeveelheid invoer", + "PurchaseAmount": "Aankoop hoeveelheid", + "PurchasedItem": "Je hebt gekocht ", + "CurrencySymbol": "€", + "Confirm": "Aankoop bevestigen", + "AreYouSure": "Weet je zeker dat je een ", + "PayByCash": "Contant betalen", + "PayByCard": "Met kaart betalen" + }, + "UNITTEST": { + "UNITTESTA": "Ik ben een %s %s", + "locale-unit-test": "Dit is een test string" + }, + "clipboard": { + "copy": "Gekopieerd naar klembord" + }, + "placeable_object": { + "no_prop_defined": "Je hebt geen object gedefinieerd om te plaatsen", + "cant_place_here": "Je kunt dit object hier niet plaatsen", + "place_object_place": "[E] Plaatsen \n", + "place_object_cancel": "[X] Annuleren \n", + "place_object_scroll_up": "[SCROLL UP] Rechts draaien \n", + "place_object_scroll_down": "[SCROLL DOWN] Links draaien" + } +} diff --git a/locales/no.json b/locales/no.json new file mode 100644 index 0000000..7318bfd --- /dev/null +++ b/locales/no.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Du har ikke nok penger til å kjøpe denne varen", + "Input": "Mengde inndata", + "PurchaseAmount": "Kjøpsmengde", + "PurchasedItem": "Du har kjøpt ", + "CurrencySymbol": "kr", + "Confirm": "Bekreft kjøp", + "AreYouSure": "Er du sikker på at du vil kjøpe en ", + "PayByCash": "Betal kontant", + "PayByCard": "Betal med kort" + }, + "UNITTEST": { + "UNITTESTA": "Jeg er en %s %s", + "locale-unit-test": "Dette er en teststreng" + }, + "clipboard": { + "copy": "Kopiert til utklippstavle" + }, + "placeable_object": { + "no_prop_defined": "Du har ikke definert noe objekt å plassere", + "cant_place_here": "Du kan ikke plassere dette objektet her", + "place_object_place": "[E] Plasser \n", + "place_object_cancel": "[X] Avbryt \n", + "place_object_scroll_up": "[SCROLL UP] Drei høyre \n", + "place_object_scroll_down": "[SCROLL DOWN] Drei venstre" + } +} diff --git a/locales/pl.json b/locales/pl.json new file mode 100644 index 0000000..050753d --- /dev/null +++ b/locales/pl.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Nie masz wystarczająco pieniędzy, aby kupić ten przedmiot", + "Input": "Wprowadzenie ilości", + "PurchaseAmount": "Ilość zakupu", + "PurchasedItem": "Kupiłeś ", + "CurrencySymbol": "zł", + "Confirm": "Potwierdź zakup", + "AreYouSure": "Czy na pewno chcesz kupić ", + "PayByCash": "Zapłać gotówką", + "PayByCard": "Zapłać kartą" + }, + "UNITTEST": { + "UNITTESTA": "Jestem %s %s", + "locale-unit-test": "To jest ciąg testowy" + }, + "clipboard": { + "copy": "Skopiowano do schowka" + }, + "placeable_object": { + "no_prop_defined": "Nie zdefiniowałeś żadnego obiektu do umieszczenia", + "cant_place_here": "Nie możesz umieścić tego obiektu tutaj", + "place_object_place": "[E] Umieść \n", + "place_object_cancel": "[X] Anuluj \n", + "place_object_scroll_up": "[SCROLL UP] Obróć w prawo \n", + "place_object_scroll_down": "[SCROLL DOWN] Obróć w lewo" + } +} diff --git a/locales/pt.json b/locales/pt.json index 2c5e0a8..46557fa 100644 --- a/locales/pt.json +++ b/locales/pt.json @@ -1,28 +1,28 @@ { - "locale-unit-test": "Isto é apenas uma string de teste", - "place_object_place": "[E] Colocar \n", - "place_object_cancel": "[X] Cancelar \n", - "place_object_scroll_up": "[SCROLL UP] Direita\n", - "place_object_scroll_down": "[SCROLL DOWN] Esquerda", - "enter_text": "Inserir Texto", - "no_prop_defined": "Não definiu nenhum objeto para colocar", - "accessibility": { - "cb_command": "daltônico", - "cb_title": "Opções de daltonismo", - "cb_desc": "Selecione seu tipo de daltonismo\nDaltonismo atual: %s", - "cb_none": "Nenhum", - "cb_updated": "O daltonismo foi atualizado para %s", - "cb_default_title": "Sem daltonismo", - "cb_default_desc": "Sem daltonismo.\nEsta é a opção padrão.", - "cb_protanomaly_title": "Protanomalia", - "cb_protanomaly_desc": "Daltonismo vermelho-verde.\nFaz com que certos tons de vermelho pareçam mais verdes e menos brilhantes.\nEste tipo é leve e geralmente não atrapalha as atividades normais.", - "cb_deuteranomaly_title": "Deuteranomalia", - "cb_deuteranomaly_desc": "Daltonismo vermelho-verde.\nFaz com que certos tons de verde pareçam mais vermelhos.\nEste tipo é leve e geralmente não atrapalha as atividades normais.", - "cb_dual_title": "Protanopia e Deuteranopia", - "cb_dual_desc": "Daltonismo vermelho-verde.\nFaz com que alguém não consiga distinguir entre vermelho e verde.", - "cb_tritanopia_title": "Tritanopia", - "cb_tritanopia_desc": "Daltonismo azul-amarelo que faz com que alguém não consiga distinguir a diferença entre azul e verde, roxo e vermelho, e amarelo e rosa.\nTambém faz com que as cores pareçam menos brilhantes.", - "cb_tritanomaly_title": "Tritanomalia", - "cb_tritanomaly_desc": "O daltonismo azul-amarelo dificulta a distinção entre azul e verde e entre amarelo e vermelho.", - } -} \ No newline at end of file + "Shops": { + "NotEnoughMoney": "Você não tem dinheiro suficiente para comprar este item", + "Input": "Entrada de quantidade", + "PurchaseAmount": "Quantidade de compra", + "PurchasedItem": "Você comprou ", + "CurrencySymbol": "R$", + "Confirm": "Confirmar compra", + "AreYouSure": "Tem certeza de que deseja comprar um ", + "PayByCash": "Pagar em dinheiro", + "PayByCard": "Pagar com cartão" + }, + "UNITTEST": { + "UNITTESTA": "Eu sou um %s %s", + "locale-unit-test": "Esta é uma string de teste" + }, + "clipboard": { + "copy": "Copiado para a área de transferência" + }, + "placeable_object": { + "no_prop_defined": "Você não definiu nenhum objeto para colocar", + "cant_place_here": "Você não pode colocar este objeto aqui", + "place_object_place": "[E] Colocar \n", + "place_object_cancel": "[X] Cancelar \n", + "place_object_scroll_up": "[SCROLL UP] Girar à direita \n", + "place_object_scroll_down": "[SCROLL DOWN] Girar à esquerda" + } +} diff --git a/locales/ro.json b/locales/ro.json new file mode 100644 index 0000000..b23895c --- /dev/null +++ b/locales/ro.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Nu aveți suficienți bani pentru a cumpăra acest articol", + "Input": "Introducere cantitate", + "PurchaseAmount": "Cantitatea de cumpărare", + "PurchasedItem": "Ați cumpărat ", + "CurrencySymbol": "lei", + "Confirm": "Confirmați achiziția", + "AreYouSure": "Sunteți sigur că doriți să cumpărați ", + "PayByCash": "Plătiți cu numerar", + "PayByCard": "Plătiți cu cardul" + }, + "UNITTEST": { + "UNITTESTA": "Sunt un %s %s", + "locale-unit-test": "Acesta este un șir de test" + }, + "clipboard": { + "copy": "Copiat în clipboard" + }, + "placeable_object": { + "no_prop_defined": "Nu ați definit niciun obiect de plasat", + "cant_place_here": "Nu puteți plasa acest obiect aici", + "place_object_place": "[E] Plasați \n", + "place_object_cancel": "[X] Anulați \n", + "place_object_scroll_up": "[SCROLL UP] Rotiți la dreapta \n", + "place_object_scroll_down": "[SCROLL DOWN] Rotiți la stânga" + } +} diff --git a/locales/ru.json b/locales/ru.json new file mode 100644 index 0000000..6a9e829 --- /dev/null +++ b/locales/ru.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "У вас недостаточно денег для покупки этого товара", + "Input": "Ввод количества", + "PurchaseAmount": "Количество покупки", + "PurchasedItem": "Вы купили ", + "CurrencySymbol": "₽", + "Confirm": "Подтвердить покупку", + "AreYouSure": "Вы уверены, что хотите купить ", + "PayByCash": "Оплатить наличными", + "PayByCard": "Оплатить картой" + }, + "UNITTEST": { + "UNITTESTA": "Я %s %s", + "locale-unit-test": "Это тестовая строка" + }, + "clipboard": { + "copy": "Скопировано в буфер обмена" + }, + "placeable_object": { + "no_prop_defined": "Вы не определили объект для размещения", + "cant_place_here": "Вы не можете разместить этот объект здесь", + "place_object_place": "[E] Разместить \n", + "place_object_cancel": "[X] Отмена \n", + "place_object_scroll_up": "[SCROLL UP] Повернуть вправо \n", + "place_object_scroll_down": "[SCROLL DOWN] Повернуть влево" + } +} diff --git a/locales/sv.json b/locales/sv.json new file mode 100644 index 0000000..eb346b7 --- /dev/null +++ b/locales/sv.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Du har inte tillräckligt med pengar för att köpa detta föremål", + "Input": "Mängd inmatning", + "PurchaseAmount": "Köpmängd", + "PurchasedItem": "Du har köpt ", + "CurrencySymbol": "kr", + "Confirm": "Bekräfta köp", + "AreYouSure": "Är du säker på att du vill köpa en ", + "PayByCash": "Betala kontant", + "PayByCard": "Betala med kort" + }, + "UNITTEST": { + "UNITTESTA": "Jag är en %s %s", + "locale-unit-test": "Detta är en teststräng" + }, + "clipboard": { + "copy": "Kopierat till urklipp" + }, + "placeable_object": { + "no_prop_defined": "Du har inte definierat något objekt att placera", + "cant_place_here": "Du kan inte placera detta objekt här", + "place_object_place": "[E] Placera \n", + "place_object_cancel": "[X] Avbryt \n", + "place_object_scroll_up": "[SCROLL UP] Vrid höger \n", + "place_object_scroll_down": "[SCROLL DOWN] Vrid vänster" + } +} diff --git a/locales/th.json b/locales/th.json new file mode 100644 index 0000000..587f5db --- /dev/null +++ b/locales/th.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "คุณไม่มีเงินเพียงพอที่จะซื้อสินค้านี้", + "Input": "ป้อนจำนวน", + "PurchaseAmount": "จำนวนการซื้อ", + "PurchasedItem": "คุณซื้อแล้ว ", + "CurrencySymbol": "฿", + "Confirm": "ยืนยันการซื้อ", + "AreYouSure": "คุณแน่ใจหรือไม่ว่าต้องการซื้อ ", + "PayByCash": "จ่ายด้วยเงินสด", + "PayByCard": "จ่ายด้วยบัตร" + }, + "UNITTEST": { + "UNITTESTA": "ฉันคือ %s %s", + "locale-unit-test": "นี่คือสตริงทดสอบ" + }, + "clipboard": { + "copy": "คัดลอกไปยังคลิปบอร์ดแล้ว" + }, + "placeable_object": { + "no_prop_defined": "คุณไม่ได้กำหนดวัตถุใดๆ ให้วาง", + "cant_place_here": "คุณไม่สามารถวางวัตถุนี้ที่นี่ได้", + "place_object_place": "[E] วาง \n", + "place_object_cancel": "[X] ยกเลิก \n", + "place_object_scroll_up": "[SCROLL UP] หมุนขวา \n", + "place_object_scroll_down": "[SCROLL DOWN] หมุนซ้าย" + } +} diff --git a/locales/tr.json b/locales/tr.json new file mode 100644 index 0000000..f3bb8e4 --- /dev/null +++ b/locales/tr.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "Bu ürünü satın almak için yeterli paranız yok", + "Input": "Miktar girişi", + "PurchaseAmount": "Satın alma miktarı", + "PurchasedItem": "Satın aldınız ", + "CurrencySymbol": "₺", + "Confirm": "Satın almayı onayla", + "AreYouSure": "Bir tane satın almak istediğinizden emin misiniz ", + "PayByCash": "Nakit ile öde", + "PayByCard": "Kart ile öde" + }, + "UNITTEST": { + "UNITTESTA": "Ben bir %s %s", + "locale-unit-test": "Bu bir test dizesi" + }, + "clipboard": { + "copy": "Panoya kopyalandı" + }, + "placeable_object": { + "no_prop_defined": "Yerleştirilecek herhangi bir nesne tanımlamadınız", + "cant_place_here": "Bu nesneyi buraya yerleştiremezsiniz", + "place_object_place": "[E] Yerleştir \n", + "place_object_cancel": "[X] İptal \n", + "place_object_scroll_up": "[SCROLL UP] Sağa çevir \n", + "place_object_scroll_down": "[SCROLL DOWN] Sola çevir" + } +} diff --git a/locales/zh-cn.json b/locales/zh-cn.json new file mode 100644 index 0000000..aed390a --- /dev/null +++ b/locales/zh-cn.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "你没有足够的钱来购买这个物品", + "Input": "数量输入", + "PurchaseAmount": "购买数量", + "PurchasedItem": "你已购买 ", + "CurrencySymbol": "¥", + "Confirm": "确认购买", + "AreYouSure": "你确定要购买一个 ", + "PayByCash": "现金支付", + "PayByCard": "刷卡支付" + }, + "UNITTEST": { + "UNITTESTA": "我是一个 %s %s", + "locale-unit-test": "这是一个测试字符串" + }, + "clipboard": { + "copy": "已复制到剪贴板" + }, + "placeable_object": { + "no_prop_defined": "你没有定义任何要放置的物体", + "cant_place_here": "你不能在这里放置这个物体", + "place_object_place": "[E] 放置 \n", + "place_object_cancel": "[X] 取消 \n", + "place_object_scroll_up": "[滚轮上] 向右转 \n", + "place_object_scroll_down": "[滚轮下] 向左转" + } +} diff --git a/locales/zh-hk.json b/locales/zh-hk.json new file mode 100644 index 0000000..8e3f87b --- /dev/null +++ b/locales/zh-hk.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "你沒有足夠的錢來購買這個物品", + "Input": "數量輸入", + "PurchaseAmount": "購買數量", + "PurchasedItem": "你已購買 ", + "CurrencySymbol": "HK$", + "Confirm": "確認購買", + "AreYouSure": "你確定要購買一個 ", + "PayByCash": "現金支付", + "PayByCard": "刷卡支付" + }, + "UNITTEST": { + "UNITTESTA": "我是一個 %s %s", + "locale-unit-test": "這是一個測試字符串" + }, + "clipboard": { + "copy": "已複製到剪貼板" + }, + "placeable_object": { + "no_prop_defined": "你沒有定義任何要放置的物體", + "cant_place_here": "你不能在這裡放置這個物體", + "place_object_place": "[E] 放置 \n", + "place_object_cancel": "[X] 取消 \n", + "place_object_scroll_up": "[滾輪上] 向右轉 \n", + "place_object_scroll_down": "[滾輪下] 向左轉" + } +} diff --git a/locales/zh-tw.json b/locales/zh-tw.json new file mode 100644 index 0000000..94ac9c1 --- /dev/null +++ b/locales/zh-tw.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "你沒有足夠的錢來購買這個物品", + "Input": "數量輸入", + "PurchaseAmount": "購買數量", + "PurchasedItem": "你已購買 ", + "CurrencySymbol": "NT$", + "Confirm": "確認購買", + "AreYouSure": "你確定要購買一個 ", + "PayByCash": "現金支付", + "PayByCard": "刷卡支付" + }, + "UNITTEST": { + "UNITTESTA": "我是一個 %s %s", + "locale-unit-test": "這是一個測試字符串" + }, + "clipboard": { + "copy": "已複製到剪貼板" + }, + "placeable_object": { + "no_prop_defined": "你沒有定義任何要放置的物體", + "cant_place_here": "你不能在這裡放置這個物體", + "place_object_place": "[E] 放置 \n", + "place_object_cancel": "[X] 取消 \n", + "place_object_scroll_up": "[滾輪上] 向右轉 \n", + "place_object_scroll_down": "[滾輪下] 向左轉" + } +} diff --git a/locales/zh.json b/locales/zh.json new file mode 100644 index 0000000..aed390a --- /dev/null +++ b/locales/zh.json @@ -0,0 +1,28 @@ +{ + "Shops": { + "NotEnoughMoney": "你没有足够的钱来购买这个物品", + "Input": "数量输入", + "PurchaseAmount": "购买数量", + "PurchasedItem": "你已购买 ", + "CurrencySymbol": "¥", + "Confirm": "确认购买", + "AreYouSure": "你确定要购买一个 ", + "PayByCash": "现金支付", + "PayByCard": "刷卡支付" + }, + "UNITTEST": { + "UNITTESTA": "我是一个 %s %s", + "locale-unit-test": "这是一个测试字符串" + }, + "clipboard": { + "copy": "已复制到剪贴板" + }, + "placeable_object": { + "no_prop_defined": "你没有定义任何要放置的物体", + "cant_place_here": "你不能在这里放置这个物体", + "place_object_place": "[E] 放置 \n", + "place_object_cancel": "[X] 取消 \n", + "place_object_scroll_up": "[滚轮上] 向右转 \n", + "place_object_scroll_down": "[滚轮下] 向左转" + } +} diff --git a/modules/accessibility/client.lua b/modules/accessibility/client.lua deleted file mode 100644 index 5aa0851..0000000 --- a/modules/accessibility/client.lua +++ /dev/null @@ -1,212 +0,0 @@ -local colourblind = GetResourceKvpString('colourblind') or "default" -local QB = false -if (BridgeClientConfig.MenuSystem == "auto" and GetResourceState("qb-menu") ~= "started") or (BridgeClientConfig.MenuSystem ~= "auto" and BridgeClientConfig.MenuSystem == "qb-menu") then - QB = true -end - -Accessibility = Accessibility or {} - -RegisterCommand(locale("accessibility.cb_command"), function() - Accessibility.updatecolourblindness() -end, false) - -Accessibility.updatecolourblindness = function() - local currentCB = locale("accessibility.cb_"..colourblind.."_title") - local cbIcon = "fas fa-eye-low-vision" - Menu.Open({ - id = 'colourblind_update', - title = locale("accessibility.cb_title"), - options = { - { - title = locale("accessibility.cb_title"), - description = locale("accessibility.cb_desc"):format(currentCB), - disabled = true, - }, - { - title = locale("accessibility.cb_default_title"), - description = locale("accessibility.cb_default_desc"), - icon = "fas fa-eye", - onSelect = function() - colourblind = "default" - SetResourceKvp('colourblind', colourblind) - Notify.SendNotify(locale("accessibility.cb_updated"):format(locale("accessibility.cb_"..colourblind.."_title")), 'success', 3000) - end - }, - { - title = locale("accessibility.cb_protanomaly_title"), - description = locale("accessibility.cb_protanomaly_desc"), - icon = cbIcon, - onSelect = function() - colourblind = "protanomaly" - SetResourceKvp('colourblind', colourblind) - Notify.SendNotify(locale("accessibility.cb_updated"):format(locale("accessibility.cb_"..colourblind.."_title")), 'success', 3000) - end - }, - { - title = locale("accessibility.cb_deuteranomaly_title"), - description = locale("accessibility.cb_deuteranomaly_desc"), - icon = cbIcon, - onSelect = function() - colourblind = "deuteranomaly" - SetResourceKvp('colourblind', colourblind) - Notify.SendNotify(locale("accessibility.cb_updated"):format(locale("accessibility.cb_"..colourblind.."_title")), 'success', 3000) - end - }, - { - title = locale('accessibility.cb_dual_title'), - description = locale("accessibility.cb_dual_desc"), - icon = cbIcon, - onSelect = function() - colourblind = "dual" - SetResourceKvp('colourblind', colourblind) - Notify.SendNotify(locale("accessibility.cb_updated"):format(locale("accessibility.cb_"..colourblind.."_title")), 'success', 3000) - end - }, - { - title = locale("accessibility.cb_tritanopia_title"), - description = locale("accessibility.cb_tritanopia_desc"), - icon = cbIcon, - onSelect = function() - colourblind = "tritanopia" - SetResourceKvp('colourblind', colourblind) - Notify.SendNotify(locale("accessibility.cb_updated"):format(locale("accessibility.cb_"..colourblind.."_title")), 'success', 3000) - end - }, - { - title = locale("accessibility.cb_tritanomaly_title"), - description = locale("accessibility.cb_tritanomaly_desc"), - icon = cbIcon, - onSelect = function() - colourblind = "tritanomaly" - SetResourceKvp('colourblind', colourblind) - Notify.SendNotify(locale("accessibility.cb_updated"):format(locale("accessibility.cb_"..colourblind.."_title")), 'success', 3000) - end - }, - }},QB) -end -Accessibility.hexToRgb = function(hex) - hex = hex:gsub("#", "") - local r,g,b = tonumber("0x" .. hex:sub(1, 2)),tonumber("0x" .. hex:sub(3, 4)),tonumber("0x" .. hex:sub(5, 6)) - return r, g, b -end - -Accessibility.rgbToHex = function(r, g, b) - return string.format("#%02x%02x%02x", r, g, b) -end - -Accessibility.rgbToHsl = function(r, g, b) - r = r / 255 - g = g / 255 - b = b / 255 - local max = math.max(r, g, b) - local min = math.min(r, g, b) - local h, s, l = 0, 0, (max + min) / 2 - - if max == min then - h, s = 0, 0 -- achromatic - else - local d = max - min - s = l > 0.5 and d / (2 - max - min) or d / (max + min) - if max == r then - h = (g - b) / d + (g < b and 6 or 0) - elseif max == g then - h = (b - r) / d + 2 - elseif max == b then - h = (r - g) / d + 4 - end - h = h / 6 - end - return h, s, l -end - -Accessibility.hslToRgb = function(h, s, l) - local r, g, b - if s == 0 then - r, g, b = l, l, l -- achromatic - else - local function hue2rgb(p, q, t) - if t < 0 then t = t + 1 end - if t > 1 then t = t - 1 end - if t < 1 / 6 then return p + (q - p) * 6 * t end - if t < 1 / 2 then return q end - if t < 2 / 3 then return p + (q - p) * (2 / 3 - t) * 6 end - return p - end - - local q = l < 0.5 and l * (1 + s) or l + s - l * s - local p = 2 * l - q - r = hue2rgb(p, q, h + 1 / 3) - g = hue2rgb(p, q, h) - b = hue2rgb(p, q, h - 1 / 3) - end - return math.floor(r * 255), math.floor(g * 255), math.floor(b * 255) -end - -Accessibility.adjustColourForColourblindness = function(num, returnAsRGB) - local r, g, b - if type(num) ~= "table" and num:match("^#%x%x%x%x%x%x$") then - r, g, b = Accessibility.hexToRgb(num) -- Convert hex to RGB - else - r, g, b = num.r, num.g, num.b -- If it's already RGB, use it directly - end - local h, s, l = Accessibility.rgbToHsl(r, g, b) -- Convert RGB to HSL - -- Adjust hue values based on colourblindness type - if colourblind == "protanomaly" then -- Red-blind - -- Shift towards blue/cyan - h = (h + 0.5) % 1 -- Shift by 180 degrees - elseif colourblind == "deuteranomaly" then -- Green-blind - -- Shift towards blue/magenta - h = (h + 0.33) % 1 -- Shift by 120 degrees - elseif colourblind == "dual" then -- Protanopia and Deuteranopia (Red-Green blind) - -- More significant shift towards blue/yellow - -- This is a more drastic shift to maximize contrast - if h < 0.166 then -- Reddish hues - h = 0.66 -- Shift to blue - elseif h < 0.5 then -- Greenish hues - h = 0.166 -- Shift to yellow - else - h = h -- Leave blue/purple hues alone - end - -- Increase saturation and lightness to make colours more distinct - s = math.min(s * 1.5, 1) - l = math.min(l * 1.2, 1) - elseif colourblind == "tritanopia" then -- Blue-blind - -- Shift towards red/yellow - h = (h + 0.16) % 1 -- Shift by 60 degrees - elseif colourblind == "tritanomaly" then - h = (h + 0.08) % 1 - end - - -- Convert back to RGB - r, g, b = Accessibility.hslToRgb(h, s, l) - if returnAsRGB then - return {r = r, g = g, b = b} - else - -- Convert back to HEX - local newHex = Accessibility.rgbToHex(r, g, b) - return newHex - end -end - ----@returns a colour adjusted for colourblindness in HEX if variable `returnAsRGB` is false ----@param colourName string Colour name in HEX format or RGB format --- This is the trigger function for altering colours for colourblindness :D -Accessibility.getAdjustedColour = function(colourName, returnAsRGB) - local originalHex = colourName - if originalHex then - if colourblind == "default" then - if type(colourName) == "table" and not returnAsRGB then - return Accessibility.rgbToHex(colourName.r, colourName.g, colourName.b) - else - return originalHex - end - else - return Accessibility.adjustColourForColourblindness(originalHex, returnAsRGB) - end - else - Prints.Error("Invalid Colour Name^0] [^3"..colourName.."^0") - return "#FFFFFF" -- Default to white if the colour name is invalid - end -end - -return Accessibility \ No newline at end of file diff --git a/modules/clothing/_default/client.lua b/modules/clothing/_default/client.lua index 47b89d4..35a84ec 100644 --- a/modules/clothing/_default/client.lua +++ b/modules/clothing/_default/client.lua @@ -3,34 +3,73 @@ Clothing = Clothing or {} ClothingBackup = {} +Callback = Callback or Require("lib/utility/shared/callbacks.lua") +Ultility = Utility or Require('lib/utility/client/utility.lua') +Cache = Cache or Require('lib/cache/shared/cache.lua') ----This will set the peds skin data to the specified table. It will also store previous skin in the event it needs returned to original. ----@param data table ----@return boolean -Clothing.SetAppearance = function(data) - ClothingBackup = Clothing.GetAppearance() - Utility.SetEntitySkinData(cache.ped, data) - return true +function Clothing.IsMale() + local ped = PlayerPedId() + if not ped then return end + if GetEntityModel(ped) == `mp_m_freemode_01` then + return true + end + return false end ----This will return a table of the players ped appearance +---Get the skin data of a ped +---@param entity number ---@return table -Clothing.GetAppearance = function() - return Utility.GetEntitySkinData(cache.ped) +function Clothing.GetAppearance(entity) + if not entity and not DoesEntityExist(entity) then return end + local model = GetEntityModel(entity) + local skinData = { model = model, components = {}, props = {} } + for i = 0, 11 do + table.insert(skinData.components, { component_id = i, drawable = GetPedDrawableVariation(entity, i), texture = GetPedTextureVariation(entity, i) }) + end + for i = 0, 13 do + table.insert(skinData.props, { prop_id = i, drawable = GetPedPropIndex(entity, i), texture = GetPedPropTextureIndex(entity, i) }) + end + return skinData end ----This will return the peds clothing to the previously stored clothing +function Clothing.CopyAppearanceToClipboard() + local ped = PlayerPedId() + if not ped or not DoesEntityExist(ped) then return end + local skinData = Clothing.GetAppearance(ped) + if not skinData then return end + Ultility.CopyToClipboard(skinData) +end + +Callback.Register('community_bridge:cb:GetAppearance', function() + local ped = PlayerPedId() + if not ped or not DoesEntityExist(ped) then return end + local skinData = Clothing.GetAppearance(ped) + return skinData +end) + +---Apply skin data to a ped +---@param entity number +---@param skinData table ---@return boolean -Clothing.RestoreAppearance = function() - Utility.SetEntitySkinData(cache.ped, ClothingBackup) +function Clothing.SetAppearance(entity, skinData) + for k, v in pairs(skinData.components or {}) do + if v.component_id then + SetPedComponentVariation(entity, v.component_id, v.drawable, v.texture, 0) + end + end + for k, v in pairs(skinData.props or {}) do + if v.prop_id then + SetPedPropIndex(entity, v.prop_id, v.drawable, v.texture, 0) + end + end return true end ----This will reload the peds skin data from the backup table. This is used when the skin data is changed and needs to be reloaded. +---This will return the peds components to the previously stored components ---@return boolean -Clothing.ReloadSkin = function() - Utility.SetEntitySkinData(cache.ped, ClothingBackup) +Clothing.RestoreAppearance = function(entity) + Clothing.SetAppearance(entity, ClothingBackup) return true end @@ -38,24 +77,111 @@ Clothing.UpdateAppearanceBackup = function(data) ClothingBackup = data end -RegisterNetEvent('community_bridge:client:updateClothingBackup', function(skindata) - ClothingBackup = skindata +Clothing.RunningDebug = false +Clothing.Cache = nil -- maybe change this to the actual cache system???!? For future not lazy me + +Cache.Create('Clothing', function() + local ped = Cache.Get('Ped') + local appearance = Clothing.GetAppearance(ped) + if Table.Compare(Clothing.Cache, appearance) then + return false + end + return appearance +end, 1000) + +local onChange = nil +Clothing.ToggleDebugging = function() + + if Clothing.RunningDebug then + Clothing.RunningDebug = false + print("Clothing Debugging Disabled") + return Cache.RemoveOnChange('Clothing', onChange) + end + Clothing.RunningDebug = true + print("Clothing Debugging Enabled") + + if Clothing.OpenMenu then + Clothing.OpenMenu() + end + + onChange = Cache.OnChange('Clothing', function(new, old) + print("Clothing Debugging", new) + for k, v in pairs(old.components) do + if v.component_id then + if new.components[k].drawable ~= v.drawable or new.components[k].texture ~= v.texture then + print("Component ID: " .. v.component_id .. " Drawable: " .. new.components[k].drawable .. " Texture: " .. new.components[k].texture) + end + end + end + for k, v in pairs(old.props) do + if v.prop_id then + if new.props[k].drawable ~= v.drawable or new.props[k].texture ~= v.texture then + print("Prop ID: " .. v.prop_id .. " Drawable: " .. new.props[k].drawable .. " Texture: " .. new.props[k].texture) + end + end + end + end) + -- CreateThread(function() + -- while Clothing.RunningDebug do + -- Wait(3) + -- local ped = PlayerPedId() + -- if ped then + -- if not Clothing.Cache then + -- Clothing.Cache = Clothing.GetAppearance(ped) + -- end + -- for k, v in pairs(Clothing.Cache.components) do + -- if v.component_id then + -- local drawable = GetPedDrawableVariation(ped, v.component_id) + -- local texture = GetPedTextureVariation(ped, v.component_id) + -- if drawable ~= v.drawable or texture ~= v.texture then + -- print("Component ID: " .. v.component_id .. " Drawable: " .. drawable .. " Texture: " .. texture) + -- Clothing.Cache.components[k].drawable = drawable + -- Clothing.Cache.components[k].texture = texture + -- end + -- end + -- end + -- for k, v in pairs(Clothing.Cache.props) do + -- if v.prop_id then + -- local drawable = GetPedPropIndex(ped, v.prop_id) + -- local texture = GetPedPropTextureIndex(ped, v.prop_id) + -- if drawable ~= v.drawable or texture ~= v.texture then + -- print("Prop ID: " .. v.prop_id .. " Drawable: " .. drawable .. " Texture: " .. texture) + -- Clothing.Cache.props[k].drawable = drawable + -- Clothing.Cache.props[k].texture = texture + -- end + -- end + -- end + -- end + -- -- esc key to exit + -- if IsControlJustPressed(0, 177) then + -- Clothing.RunningDebug = false + -- print("Clothing Debugging Disabled") + -- end + -- end + -- Clothing.Cache = nil + -- end) +end + +RegisterCommand("clothing:enabledebug", function(source, args, rawCommand) + Clothing.ToggleDebugging() end) RegisterNetEvent('community_bridge:client:SetAppearance', function(data) - Clothing.SetAppearance(data) + Clothing.SetAppearance(PlayerPedId(), data) end) RegisterNetEvent('community_bridge:client:GetAppearance', function() - Clothing.GetAppearance() + Clothing.GetAppearance(PlayerPedId()) end) RegisterNetEvent('community_bridge:client:RestoreAppearance', function() - Clothing.RestoreAppearance() + Clothing.RestoreAppearance(PlayerPedId()) end) -RegisterNetEvent('community_bridge:client:ReloadSkin', function() - Clothing.ReloadSkin() +RegisterCommand("clothing:copy", function(source, args, rawCommand) + Clothing.CopyAppearanceToClipboard() end) + + return Clothing \ No newline at end of file diff --git a/modules/clothing/_default/server.lua b/modules/clothing/_default/server.lua index d02f61f..6c42e0f 100644 --- a/modules/clothing/_default/server.lua +++ b/modules/clothing/_default/server.lua @@ -1,34 +1,58 @@ --[[This module is incomplete]]-- Clothing = Clothing or {} +Clothing.LastAppearance = Clothing.LastAppearance or {} +Callback = Callback or Require("lib/utility/shared/callbacks.lua") + +function Clothing.IsMale(src) + local ped = GetPlayerPed(src) + if not ped or not DoesEntityExist(ped) then return end + return GetEntityModel(ped) == `mp_m_freemode_01` +end + + +function Clothing.GetAppearance(src) + return Callback.Trigger('community_bridge:cb:GetAppearance', src) +end Clothing.SetAppearance = function(src, data) + local strSrc = tostring(src) + Clothing.LastAppearance[strSrc] = Clothing.GetAppearance(src) TriggerClientEvent('community_bridge:client:SetAppearance', src, data) end +--- Sets a player's appearance based on gender-specific data +---@param src number The server ID of the player +---@param data table Table containing separate appearance data for male and female characters +---@return table|nil Appearance updated player appearance data or nil if failed +function Clothing.SetAppearanceExt(src, data) + local tbl = Clothing.IsMale(src) and data.male or data.female + Clothing.SetAppearance(src, tbl) +end + Clothing.RestoreAppearance = function(src) TriggerClientEvent('community_bridge:client:RestoreAppearance', src) end -Clothing.ReloadSkin = function(src) - TriggerClientEvent('community_bridge:client:ReloadSkin', src) -end +-- RegisterNetEvent('community_bridge:client:SetAppearance', function(data) +-- local src = source +-- Clothing.SetAppearance(src, data) +-- end) -RegisterNetEvent('community_bridge:client:SetAppearance', function(data) - Clothing.SetAppearance(data) -end) +-- RegisterNetEvent('community_bridge:client:GetAppearance', function() +-- local src = source +-- Clothing.GetAppearance(src) +-- end) -RegisterNetEvent('community_bridge:client:GetAppearance', function() - Clothing.GetAppearance() -end) +-- RegisterNetEvent('community_bridge:client:RestoreAppearance', function() +-- local src = source +-- Clothing.RestoreAppearance(src) +-- end) -RegisterNetEvent('community_bridge:client:RestoreAppearance', function() - Clothing.RestoreAppearance() -end) - -RegisterNetEvent('community_bridge:client:ReloadSkin', function() - Clothing.ReloadSkin() -end) +-- RegisterNetEvent('community_bridge:client:ReloadSkin', function() +-- local src = source +-- Clothing.ReloadSkin(src) +-- end) return Clothing \ No newline at end of file diff --git a/modules/clothing/esx_skin/client.lua b/modules/clothing/esx_skin/client.lua new file mode 100644 index 0000000..3f1d870 --- /dev/null +++ b/modules/clothing/esx_skin/client.lua @@ -0,0 +1,7 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('esx_skin') == 'missing' then return end +Clothing = Clothing or {} + +function Clothing.OpenMenu() + TriggerEvent('esx_skin:openMenu', function()end, function()end, true) +end \ No newline at end of file diff --git a/modules/clothing/esx_skin/server.lua b/modules/clothing/esx_skin/server.lua new file mode 100644 index 0000000..5e2d8c4 --- /dev/null +++ b/modules/clothing/esx_skin/server.lua @@ -0,0 +1,212 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('esx_skin') == 'missing' then return end +Clothing = Clothing or {} +Clothing.Players = {} + +Callback = Callback or Require("lib/utility/shared/callbacks.lua") +Table = Table or Require('lib/utility/shared/tables.lua') +ESX = ESX or exports['es_extended']:getSharedObject() + +---Internal function to get the full appearance data including skin, model, and converted format +---@param src number The server ID of the player +---@return table|nil The player's full appearance data or nil if not found +function Clothing.GetFullAppearanceData(src) + src = src and tonumber(src) + assert(src, "src is nil") + local Player = ESX.GetPlayerFromId(src) + if not Player then return end + local citId = Player.identifier + if not citId then return end + + if Clothing.Players[citId] then return Clothing.Players[citId] end + + local result = MySQL.query.await('SELECT skin FROM users WHERE identifier = ?', { citId}) + if result[1] == nil then return end + + local model = GetEntityModel(GetPlayerPed(src)) + local skinData = json.decode(result[1].skin) + local converted = Clothing.ConvertToDefault(skinData) + + -- Store complete data in the cache + Clothing.Players[citId] = { + model = model, + skin = skinData, + converted = converted + } + + return Clothing.Players[citId] +end + +---Retrieves a player's converted appearance data for easy use across modules +---@param src number The server ID of the player +---@param fullData boolean Optional - If true, returns the full data object including skin and model +---@return table|nil The player's converted appearance data or full appearance data if fullData=true +function Clothing.GetAppearance(src, fullData) + if fullData then + return Clothing.GetFullAppearanceData(src) + end + local completeData = Clothing.GetFullAppearanceData(src) + if not completeData then return nil end + return completeData.converted +end + +---This will save the player's current appearance to the database +---@param src number|string +function Clothing.Save(src) + src = src and tonumber(src) + assert(src, "src is nil") + local Player = ESX.GetPlayerFromId(src) + if not Player then return end + local citId = Player.identifier + if not citId then return end + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + local currentSkin = currentClothing.skin + local encodedSkin = json.encode(currentSkin) + MySQL.update.await('UPDATE users SET skin = ? WHERE identifier = ?', { + encodedSkin, + citId + }) +end +---Sets a player's appearance based on the provided data +---@param src number The server ID of the player +---@param data table The appearance data to apply +---@param updateBackup boolean Whether to update the backup appearance data +---@return table|nil The updated player appearance data or nil if failed +function Clothing.SetAppearance(src, data, updateBackup, save) + src = src and tonumber(src) + assert(src, "src is nil") + local Player = ESX.GetPlayerFromId(src) + if not Player then return end + local citId = Player.identifier + if not citId then return end + local model = GetEntityModel(GetPlayerPed(src)) + if not model then return end + local converted = Clothing.ConvertFromDefault(data) + + -- Get full appearance data + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + + local currentSkin = currentClothing.skin + for k, v in pairs(converted) do + currentSkin[k] = v + end + + + if not Clothing.Players[citId].backup or updateBackup then + Clothing.Players[citId].backup = currentClothing.converted + end + + Clothing.Players[citId] = Clothing.Players[citId] or {} + Clothing.Players[citId].skin = currentSkin + Clothing.Players[citId].model = model + Clothing.Players[citId].converted = Clothing.ConvertToDefault(currentSkin) + if save then + local encodedSkin = json.encode(currentSkin) + -- saving 1 sql call by adding the query here instead of calling save + MySQL.update.await('UPDATE users SET skin = ? WHERE identifier = ?', { + encodedSkin, + citId + }) + end + TriggerClientEvent('community_bridge:client:SetAppearance', src, Clothing.Players[citId].converted) + return Clothing.Players[citId] +end + +--- Sets a player's appearance based on gender-specific data +---@param src number The server ID of the player +---@param data table Table containing separate appearance data for male and female characters +---@return table|nil Appearance updated player appearance data or nil if failed +function Clothing.SetAppearanceExt(src, data) + local tbl = Clothing.IsMale(src) and data.male or data.female + Clothing.SetAppearance(src, tbl) +end + +---Reverts a player's appearance to their backup appearance +---@param src number The server ID of the player +---@return boolean|nil Returns true if successful or nil if failed +function Clothing.Revert(src) + src = src and tonumber(src) + assert(src, "src is nil") + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + local backup = currentClothing.backup + if not backup then return end + return Clothing.SetAppearance(src, backup) +end + +---This will open the menu for the passed src +---@param src number|string +function Clothing.OpenMenu(src) + src = src and tonumber(src) + assert(src, "src is nil") + TriggerClientEvent('esx_skin:openMenu', src) +end + +---Event handler for when a player loads into the server +---Caches the player's appearance data +AddEventHandler('community_bridge:Server:OnPlayerLoaded', function(src) + src = src and tonumber(src) + assert(src, "src is nil") + -- Use GetFullAppearanceData to cache the complete appearance + Clothing.GetFullAppearanceData(src) +end) + +---Event handler for when a player disconnects from the server +---Removes the player's appearance data from the cache +AddEventHandler('community_bridge:Server:OnPlayerUnload', function(src) + src = src and tonumber(src) + assert(src, "src is nil") + local strSrc = tostring(src) + Clothing.Players[strSrc] = nil +end) + + + +---Event handler for when the resource starts +---Caches appearance data for all currently connected players +AddEventHandler('onResourceStart', function(resource) + if resource ~= GetCurrentResourceName() then return end + for _, playerId in ipairs(GetPlayers()) do + local src = tonumber(playerId) + local strSrc = tostring(src) + if not Clothing.Players[strSrc] then + Clothing.Players[strSrc] = Clothing.GetAppearance(src) + end + end +end) + +---Callback handler for retrieving a player's appearance data +Callback.Register('community_bridge:cb:GetAppearance', function(source) + local src = source + return Clothing.GetAppearance(src) +end) + +RegisterCommand('clothing:debug', function(source, args, rawCommand) + local src = source + Clothing.SetAppearance(src, { + components ={ + {component_id = 1, drawable = math.random(0, 50), texture = 0}, + {component_id = 2, drawable = math.random(0, 50), texture = 0}, + {component_id = 3, drawable = math.random(0, 50), texture = 0}, + {component_id = 4, drawable = math.random(0, 50), texture = 0}, + {component_id = 5, drawable = math.random(0, 50), texture = 0}, + {component_id = 6, drawable = math.random(0, 50), texture = 0}, + {component_id = 7, drawable = math.random(0, 50), texture = 0}, + {component_id = 8, drawable = math.random(0, 50), texture = 0}, + }, + props = { + {prop_id = 3, drawable = 0, texture = 0}, + {prop_id = 1, drawable = 0, texture = 0}, + {prop_id = 2, drawable = 0, texture = 0}, + } + }) +end, false) + + +RegisterCommand('clothing:revert', function(source, args, rawCommand) + local src = source + Clothing.Revert(src) +end, false) + diff --git a/modules/clothing/esx_skin/shared.lua b/modules/clothing/esx_skin/shared.lua new file mode 100644 index 0000000..f8c3cea --- /dev/null +++ b/modules/clothing/esx_skin/shared.lua @@ -0,0 +1,216 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('esx_skin') == 'missing' then return end + +Clothing = Clothing or {} + +-- {"glasses_2":0,"shoes_1":70,"dad":0,"shoes_2":2,"pants_1":28,"eye_squint":0,"ears_1":-1,"hair_color_1":61,"eyebrows_6":0,"bodyb_3":-1,"beard_1":11,"complexion_2":0,"arms_2":0,"hair_1":76,"nose_1":0,"blush_2":0,"bracelets_2":0,"blush_1":0,"jaw_2":0,"helmet_1":-1,"eyebrows_3":0,"watches_1":-1,"eyebrows_4":0,"jaw_1":0,"lipstick_1":0,"eyebrows_1":0,"nose_4":0,"age_2":0,"torso_1":23,"hair_2":0,"chin_2":0,"arms":1,"chain_1":22,"nose_2":0,"cheeks_1":2,"tshirt_1":4,"glasses_1":0,"pants_2":3,"lipstick_4":0,"chin_13":0,"beard_4":0,"beard_3":0,"chain_2":2,"cheeks_3":6,"sex":0,"lipstick_3":0,"makeup_1":0,"hair_color_2":29,"mask_2":0,"chin_1":0,"eyebrows_5":0,"bodyb_2":0,"sun_2":0,"watches_2":0,"sun_1":0,"chin_4":0,"nose_3":0,"helmet_2":0,"bags_2":0,"moles_2":0,"mask_1":0,"blemishes_2":0,"chest_1":0,"cheeks_2":-10,"age_1":0,"chest_2":0,"beard_2":10,"torso_2":2,"blush_3":0,"bproof_1":0,"moles_1":0,"chin_3":0,"lip_thickness":-2,"lipstick_2":0,"chest_3":0,"complexion_1":0,"bodyb_4":0,"neck_thickness":0,"bproof_2":0,"makeup_3":0,"tshirt_2":2,"makeup_2":0,"makeup_4":0,"bracelets_1":-1,"decals_2":0,"nose_6":0,"bodyb_1":-1,"bags_1":0,"blemishes_1":0,"decals_1":0,"mom":21,"eyebrows_2":0,"eye_color":0,"skin_md_weight":50,"face_md_weight":50,"nose_5":10,"ears_2":0} + +Components = {} +Components.Map = { + [1] = 'mask', -- componentId + [2] = 'ears', + [3] = 'arms', + [4] = 'pants', + [5] = 'bags', + [6] = 'shoes', + [7] = 'chain', + [8] = 'tshirt', + [9] = 'bproof', + [10] = 'decals', + [11] = 'torso' +} + +Components.InverseMap = { + mask = 1, -- componentId + arms = 3, + pants = 4, + bags = 5, + shoes = 6, + chain = 7, + tshirt = 8, + bproof = 9, + decals = 10, + torso = 11, +} + +Props = {} +Props.Map = { + [0] = 'helmet', -- propId + [1] = 'glasses', + [2] = 'ears', + [6] = 'watches', + [7] = 'bracelets' +} + +Props.InverseMap = { + helmet_1 = 0, + helmet_2 = 0, + glasses_1 = 1, + glasses_2 = 1, + ears_1 = 2, + ears_2 = 2, + watches_1 = 6, + watches_2 = 6, + bracelets_1 = 7, + bracelets_2 = 7, +} + +-- Converts from illinium format to esx format +function Components.ConvertFromDefault(defaultComponents) + local returnComponents = {} + for index, componentData in pairs(defaultComponents or {}) do + local componentId = Components.Map[componentData.component_id] + if componentId then + returnComponents[componentId .. '_1'] = componentData.drawable + returnComponents[componentId .. '_2'] = componentData.texture + end + end + return returnComponents +end + +function Components.ConvertToDefault(esxComponents) + local returnComponents = {} + for componentIndex, componentData in pairs(esxComponents or {}) do + local isTexture = componentIndex:find('_2') + componentIndex = componentIndex:gsub('_1', ''):gsub('_2', '') + local componentId = Components.InverseMap[componentIndex] + if componentId then + if isTexture then + returnComponents[componentId] = returnComponents[componentId] or {} + returnComponents[componentId].texture = componentData + else + returnComponents[componentId] = returnComponents[componentId] or {} + returnComponents[componentId].component_id = componentId + returnComponents[componentId].drawable = componentData + returnComponents[componentId].texture = returnComponents[componentId].texture or 0 + end + end + end + return returnComponents +end + +function Props.ConvertFromDefault(defaultProps) + local returnProps = {} + for index, propData in pairs(defaultProps or {}) do + local propId = Props.Map[propData.prop_id] + if propId then + returnProps[propId .. '_1'] = propData.drawable + returnProps[propId .. '_2'] = propData.texture + end + end + return returnProps +end + +function Props.ConvertToDefault(esxProps) + local returnProps = {} + for propIndex, propData in pairs(esxProps or {}) do + local isTexture = propIndex:find('_2') + propIndex = propIndex:gsub('_1', ''):gsub('_2', '') + local propId = Props.InverseMap[propIndex] + if propId then + if isTexture then + returnProps[propId] = returnProps[propId] or {} + returnProps[propId].texture = propData + else + returnProps[propId] = returnProps[propId] or {} + returnProps[propId].prop_id = propId + returnProps[propId].drawable = propData + returnProps[propId].texture = returnProps[propId].texture or 0 + end + end + table.sort(returnProps, function(a, b) + return a.prop_id < b.prop_id + end) + end + return returnProps +end + +function Clothing.ConvertFromDefault(defaultClothing) + local components = Components.ConvertFromDefault(defaultClothing.components) + local props = Props.ConvertFromDefault(defaultClothing.props) + + for propsIndex, propData in pairs(props) do + components[propsIndex] = propData + end + + return components --skin +end + +function Clothing.ConvertToDefault(esxClothing) + local components = Components.ConvertToDefault(esxClothing) + local props = Props.ConvertToDefault(esxClothing) + return { components = components, props = props } +end + + + + + + + + + + + + + + +-- Clothing = {} + +-- StoredOldClothing = {} + +-- Clothing.SetAppearance = function(clothingData) +-- if GetEntityModel(cache.ped) == `mp_m_freemode_01` then +-- clothingData = clothingData.male +-- else +-- clothingData = clothingData.female +-- end +-- local repackedTable = {} +-- local componentMap = { +-- [1] = "mask", +-- [3] = "arms", +-- [4] = "pants", +-- [5] = "bag", +-- [6] = "shoes", +-- [7] = "accessory", +-- [8] = "t-shirt", +-- [9] = "vest", +-- [10] = "decals", +-- [11] = "torso2" +-- } + +-- local propMap = { +-- [0] = "hat", +-- [1] = "glass", +-- [2] = "ear", +-- [6] = "watch", +-- [7] = "bracelet" +-- } + +-- local specialMap = { +-- eye_color_id = "eye_color", +-- moles_id = "moles", +-- ageing_id = "ageing", +-- hair_id = "hair", +-- face_id = "face" +-- } + +-- for _, data in pairs(clothingData) do +-- if componentMap[data.component_id] then +-- repackedTable[componentMap[data.component_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif propMap[data.prop_id] then +-- repackedTable[propMap[data.prop_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.eye_color_id] then +-- repackedTable[specialMap[data.eye_color_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.moles_id] then +-- repackedTable[specialMap[data.moles_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.ageing_id] then +-- repackedTable[specialMap[data.ageing_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.hair_id] then +-- repackedTable[specialMap[data.hair_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.face_id] then +-- repackedTable[specialMap[data.face_id]] = {drawable = data.drawable, texture = data.texture} +-- end +-- end +-- TriggerEvent('esx-clothing:client:loadOutfit', repackedTable) +-- end \ No newline at end of file diff --git a/modules/clothing/fivem-appearance/client.lua b/modules/clothing/fivem-appearance/client.lua new file mode 100644 index 0000000..dcf0bfe --- /dev/null +++ b/modules/clothing/fivem-appearance/client.lua @@ -0,0 +1,8 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('fivem-appearance') == 'missing' then return end +Clothing = Clothing or {} + +function Clothing.OpenMenu() + TriggerEvent('qb-clothing:client:openMenu') +end + diff --git a/modules/clothing/fivem-appearance/server.lua b/modules/clothing/fivem-appearance/server.lua new file mode 100644 index 0000000..4235be8 --- /dev/null +++ b/modules/clothing/fivem-appearance/server.lua @@ -0,0 +1,340 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('fivem-appearance') == 'missing' then return end +Clothing = Clothing or {} +Clothing.Players = {} + +Callback = Callback or Require("lib/utility/shared/callbacks.lua") +Table = Table or Require('lib/utility/shared/tables.lua') + +--- Internal function to get the full appearance data including skin, model, and converted format +---@param src number The server ID of the player +---@return table|nil The player's full appearance data or nil if not found +function Clothing.GetFullAppearanceData(src) + src = src and tonumber(src) + assert(src, "src is nil") + local citId = Bridge.Framework.GetPlayerIdentifier(src) + if not citId then return end + + if Clothing.Players[citId] then return Clothing.Players[citId] end + + local result = MySQL.query.await('SELECT * FROM playerskins WHERE citizenid = ? AND active = ?', { citId, 1 }) + if result[1] == nil then return end + + local model = result[1].model + local skinData = json.decode(result[1].skin) + local converted = skinData + + -- Store complete data in the cache + Clothing.Players[citId] = { + model = model, + skin = skinData, + converted = converted + } + + return Clothing.Players[citId] +end + +--- Retrieves a player's converted appearance data for easy use across modules +---@param src number The server ID of the player +---@param fullData boolean Optional - If true, returns the full data object including skin and model +---@return table|nil The player's converted appearance data or full appearance data if fullData=true +function Clothing.GetAppearance(src, fullData) + if fullData then + return Clothing.GetFullAppearanceData(src) + end + local completeData = Clothing.GetFullAppearanceData(src) + if not completeData then return nil end + return completeData.converted +end + +--- Sets a player's appearance based on the provided data +---@param src number The server ID of the player +---@param data table The appearance data to apply +---@param updateBackup boolean Whether to update the backup appearance data +---@return table|nil The updated player appearance data or nil if failed +function Clothing.SetAppearance(src, data, updateBackup, save) + src = src and tonumber(src) + assert(src, "src is nil") + local citId = Bridge.Framework.GetPlayerIdentifier(src) + if not citId then return end + local model = GetEntityModel(GetPlayerPed(src)) + if not model then return end + local converted = data + + -- Get full appearance data + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + + local currentSkin = currentClothing.skin + for k, v in pairs(converted) do + currentSkin[k] = v + end + + if not Clothing.Players[citId].backup or updateBackup then + Clothing.Players[citId].backup = currentClothing.converted + end + + Clothing.Players[citId] = Clothing.Players[citId] or {} + Clothing.Players[citId].skin = currentSkin + Clothing.Players[citId].model = model + Clothing.Players[citId].converted = converted + if save then + MySQL.update.await('UPDATE playerskins SET skin = ? WHERE citizenid = ? AND active = ?', { + json.encode(currentSkin), + citId, + 1 + }) + end + TriggerClientEvent('community_bridge:client:SetAppearance', src, Clothing.Players[citId].converted) + return Clothing.Players[citId] +end + +--- Sets a player's appearance based on gender-specific data +---@param src number The server ID of the player +---@param data table Table containing separate appearance data for male and female characters +---@return table|nil Appearance updated player appearance data or nil if failed +function Clothing.SetAppearanceExt(src, data) + local tbl = Clothing.IsMale(src) and data.male or data.female + Clothing.SetAppearance(src, tbl) +end + +--- Reverts a player's appearance to their backup appearance +---@param src number The server ID of the player +---@return boolean|nil Returns true if successful or nil if failed +function Clothing.Revert(src) + src = src and tonumber(src) + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + local backup = currentClothing.backup + if not backup then return end + return Clothing.SetAppearance(src, backup) +end + +function Clothing.OpenMenu(src) + src = src and tonumber(src) + assert(src, "src is nil") + TriggerClientEvent('qb-clothing:client:openMenu', src) -- does this event work while on esx? +end + +--- Event handler for when a player loads into the server +--- Caches the player's appearance data +AddEventHandler('community_bridge:Server:OnPlayerLoaded', function(src) + src = src and tonumber(src) + assert(src, "src is nil") + -- Use GetFullAppearanceData to cache the complete appearance + Clothing.GetFullAppearanceData(src) +end) + +--- Event handler for when a player disconnects from the server +--- Removes the player's appearance data from the cache +AddEventHandler('community_bridge:Server:OnPlayerUnload', function(src) + src = src and tonumber(src) + assert(src, "src is nil") + local strSrc = tostring(src) + Clothing.Players[strSrc] = nil +end) + + + +--- Event handler for when the resource starts +--- Caches appearance data for all currently connected players +AddEventHandler('onResourceStart', function(resource) + if resource ~= GetCurrentResourceName() then return end + for _, playerId in ipairs(GetPlayers()) do + local src = tonumber(playerId) + local strSrc = tostring(src) + if not Clothing.Players[strSrc] then + Clothing.Players[strSrc] = Clothing.GetAppearance(src) + end + end +end) + +--- Callback handler for retrieving a player's appearance data +Callback.Register('community_bridge:cb:GetAppearance', function(source) + local src = source + return Clothing.GetAppearance(src) +end) + + +RegisterCommand('clothing:debug', function(source, args, rawCommand) + local src = source + Clothing.SetAppearance(src, { + components ={ + {component_id = 1, drawable = math.random(0, 50), texture = 0}, + {component_id = 2, drawable = math.random(0, 50), texture = 0}, + {component_id = 3, drawable = math.random(0, 50), texture = 0}, + {component_id = 4, drawable = math.random(0, 50), texture = 0}, + {component_id = 5, drawable = math.random(0, 50), texture = 0}, + {component_id = 6, drawable = math.random(0, 50), texture = 0}, + {component_id = 7, drawable = math.random(0, 50), texture = 0}, + {component_id = 8, drawable = math.random(0, 50), texture = 0}, + }, + props = { + {prop_id = 3, drawable = 0, texture = 0}, + {prop_id = 1, drawable = 0, texture = 0}, + {prop_id = 2, drawable = 0, texture = 0}, + } + }, false, true) +end, false) + + +RegisterCommand('clothing:revert', function(source, args, rawCommand) + local src = source + Clothing.Revert(src) +end, false) + + +RegisterCommand('clothing:current', function(source, args, rawCommand) + local src = source + local currentClothing = Clothing.GetAppearance(src) + if not currentClothing then return end + print(json.encode(currentClothing, { indent = true })) +end, false) + +RegisterCommand('clothing:openmenu', function(source, args, rawCommand) + local src = source + Clothing.OpenMenu(src) +end, false) + + +-- This should be moved into unit tests +-- RegisterCommand('clothing:crowley', function(source, args, rawCommand) +-- local src = source +-- Clothing.SetAppearance(src, { +-- components= { +-- { +-- drawable= 0, +-- texture= 0, +-- component_id= 0 +-- }, +-- { +-- drawable= 0, +-- texture= 0, +-- component_id= 1 +-- }, +-- { +-- drawable= 19, +-- texture= 0, +-- component_id= 2 +-- }, +-- { +-- drawable= 6, +-- texture= 0, +-- component_id= 3 +-- }, +-- { +-- drawable= 0, +-- texture= 0, +-- component_id= 4 +-- }, +-- { +-- drawable= 0, +-- texture= 0, +-- component_id= 5 +-- }, +-- { +-- drawable= 0, +-- texture= 0, +-- component_id= 6 +-- }, +-- { +-- drawable= 0, +-- texture= 0, +-- component_id= 7 +-- }, +-- { +-- drawable= 23, +-- texture= 0, +-- component_id= 8 +-- }, +-- { +-- drawable= 0, +-- texture= 0, +-- component_id= 9 +-- }, +-- { +-- drawable= 0, +-- texture= 0, +-- component_id= 10 +-- }, +-- { +-- drawable= 4, +-- texture= 2, +-- component_id= 11 +-- } +-- }, +-- props= { +-- { +-- drawable= 27, +-- prop_id= 0, +-- texture= 0 +-- }, +-- { +-- drawable= -1, +-- prop_id= 1, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 2, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 3, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 4, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 5, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 6, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 7, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 8, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 9, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 10, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 11, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 12, +-- texture= -1 +-- }, +-- { +-- drawable= -1, +-- prop_id= 13, +-- texture= -1 +-- } +-- }, +-- model= 1885233650 +-- }, false, true) +-- end, false) diff --git a/modules/clothing/fivem-appearance/shared.lua b/modules/clothing/fivem-appearance/shared.lua new file mode 100644 index 0000000..e454553 --- /dev/null +++ b/modules/clothing/fivem-appearance/shared.lua @@ -0,0 +1,43 @@ + + +-- { +-- male = { +-- name = "Short Sleeve", +-- outfitData = { +-- ["pants"] = {item = 133, texture = 0}, -- Pants +-- ["arms"] = {item = 31, texture = 0}, -- Arms +-- ["t-shirt"] = {item = 35, texture = 0}, -- T Shirt +-- ["vest"] = {item = 34, texture = 0}, -- Body Vest +-- ["torso2"] = {item = 48, texture = 0}, -- Jacket +-- ["shoes"] = {item = 52, texture = 0}, -- Shoes +-- ["accessory"] = {item = 0, texture = 0}, -- Neck Accessory +-- ["bag"] = {item = 0, texture = 0}, -- Bag +-- ["hat"] = {item = 0, texture = 0}, -- Hat +-- ["glass"] = {item = 0, texture = 0}, -- Glasses +-- ["mask"] = {item = 0, texture = 0} -- Mask +-- }, +-- grades = {0, 1, 2, 3, 4}, +-- }, +-- female = { +-- name = "Short Sleeve", +-- outfitData = { +-- ["pants"] = {item = 133, texture = 0}, -- Pants +-- ["arms"] = {item = 31, texture = 0}, -- Arms +-- ["t-shirt"] = {item = 35, texture = 0}, -- T Shirt +-- ["vest"] = {item = 34, texture = 0}, -- Body Vest +-- ["torso2"] = {item = 48, texture = 0}, -- Jacket +-- ["shoes"] = {item = 52, texture = 0}, -- Shoes +-- ["accessory"] = {item = 0, texture = 0}, -- Neck Accessory +-- ["bag"] = {item = 0, texture = 0}, -- Bag +-- ["hat"] = {item = 0, texture = 0}, -- Hat +-- ["glass"] = {item = 0, texture = 0}, -- Glasses +-- ["mask"] = {item = 0, texture = 0} -- Mask +-- }, +-- } +-- } + +-- function Clothing.ConvertData(data) +-- return data +-- end + +-- This still needed? \ No newline at end of file diff --git a/modules/clothing/illenium-appearance/client.lua b/modules/clothing/illenium-appearance/client.lua new file mode 100644 index 0000000..d001e7e --- /dev/null +++ b/modules/clothing/illenium-appearance/client.lua @@ -0,0 +1,8 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('illenium-appearance') == 'missing' then return end +Clothing = Clothing or {} + +function Clothing.OpenMenu() + TriggerEvent('qb-clothing:client:openMenu') +end + diff --git a/modules/clothing/illenium-appearance/server.lua b/modules/clothing/illenium-appearance/server.lua new file mode 100644 index 0000000..b78c1b2 --- /dev/null +++ b/modules/clothing/illenium-appearance/server.lua @@ -0,0 +1,252 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('illenium-appearance') == 'missing' then return end +Clothing = Clothing or {} +Clothing.Players = {} + +Callback = Callback or Require("lib/utility/shared/callbacks.lua") +Table = Table or Require('lib/utility/shared/tables.lua') + +--- Internal function to get the full appearance data including skin, model, and converted format +---@param src number The server ID of the player +---@return table|nil The player's full appearance data or nil if not found +function Clothing.GetFullAppearanceData(src) + src = src and tonumber(src) + assert(src, "src is nil") + local citId = Bridge.Framework.GetPlayerIdentifier(src) + if not citId then return end + + if Clothing.Players[citId] then return Clothing.Players[citId] end + + local result = MySQL.query.await('SELECT * FROM playerskins WHERE citizenid = ? AND active = ?', { citId, 1 }) + if result[1] == nil then return end + + local model = result[1].model + local skinData = json.decode(result[1].skin) + local converted = skinData + + -- Store complete data in the cache + Clothing.Players[citId] = { + model = model, + skin = skinData, + converted = converted + } + + return Clothing.Players[citId] +end + +--- Retrieves a player's converted appearance data for easy use across modules +---@param src number The server ID of the player +---@param fullData boolean Optional - If true, returns the full data object including skin and model +---@return table|nil The player's converted appearance data or full appearance data if fullData=true +function Clothing.GetAppearance(src, fullData) + if fullData then + return Clothing.GetFullAppearanceData(src) + end + local completeData = Clothing.GetFullAppearanceData(src) + if not completeData then return nil end + return completeData.converted +end + +--- Sets a player's appearance based on the provided data +---@param src number The server ID of the player +---@param data table The appearance data to apply +---@param updateBackup boolean Whether to update the backup appearance data +---@return table|nil The updated player appearance data or nil if failed +function Clothing.SetAppearance(src, data, updateBackup, save) + src = src and tonumber(src) + assert(src, "src is nil") + local citId = Bridge.Framework.GetPlayerIdentifier(src) + if not citId then return end + local model = GetEntityModel(GetPlayerPed(src)) + if not model then return end + local converted = data + + -- Get full appearance data + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + + local currentSkin = currentClothing.skin + for k, v in pairs(converted) do + currentSkin[k] = v + end + + if not Clothing.Players[citId].backup or updateBackup then + Clothing.Players[citId].backup = currentClothing.converted + end + + Clothing.Players[citId] = Clothing.Players[citId] or {} + Clothing.Players[citId].skin = currentSkin + Clothing.Players[citId].model = model + Clothing.Players[citId].converted = converted + if save then + MySQL.update.await('UPDATE playerskins SET skin = ? WHERE citizenid = ? AND active = ?', { + json.encode(currentSkin), + citId, + 1 + }) + end + TriggerClientEvent('community_bridge:client:SetAppearance', src, Clothing.Players[citId].converted) + return Clothing.Players[citId] +end + +--- Sets a player's appearance based on gender-specific data +---@param src number The server ID of the player +---@param data table Table containing separate appearance data for male and female characters +---@return table|nil Appearance updated player appearance data or nil if failed +function Clothing.SetAppearanceExt(src, data) + local tbl = Clothing.IsMale(src) and data.male or data.female + Clothing.SetAppearance(src, tbl) +end + +--- Reverts a player's appearance to their backup appearance +---@param src number The server ID of the player +---@return boolean|nil Returns true if successful or nil if failed +function Clothing.Revert(src) + src = src and tonumber(src) + assert(src, "src is nil") + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + local backup = currentClothing.backup + print(src, backup) + if not backup then return end + return Clothing.SetAppearance(src, backup) +end + +function Clothing.OpenMenu(src) + src = src and tonumber(src) + assert(src, "src is nil") + TriggerClientEvent('qb-clothing:client:openMenu', src) +end + +--- Event handler for when a player loads into the server +--- Caches the player's appearance data +AddEventHandler('community_bridge:Server:OnPlayerLoaded', function(src) + src = src and tonumber(src) + assert(src, "src is nil") + -- Use GetFullAppearanceData to cache the complete appearance + Clothing.GetFullAppearanceData(src) +end) + +--- Event handler for when a player disconnects from the server +--- Removes the player's appearance data from the cache +AddEventHandler('community_bridge:Server:OnPlayerUnload', function(src) + src = src and tonumber(src) + assert(src, "src is nil") + local strSrc = tostring(src) + Clothing.Players[strSrc] = nil +end) + + + +--- Event handler for when the resource starts +--- Caches appearance data for all currently connected players +AddEventHandler('onResourceStart', function(resource) + if resource ~= GetCurrentResourceName() then return end + for _, playerId in ipairs(GetPlayers()) do + local src = tonumber(playerId) + local strSrc = tostring(src) + if not Clothing.Players[strSrc] then + Clothing.Players[strSrc] = Clothing.GetAppearance(src) + end + end +end) + +--- Callback handler for retrieving a player's appearance data +Callback.Register('community_bridge:cb:GetAppearance', function(source) + local src = source + return Clothing.GetAppearance(src) +end) + +-- The below Should go to unit test +RegisterCommand('clothing:debug', function(source, args, rawCommand) + local src = source + Clothing.SetAppearance(src, { + components ={ + {component_id = 0, drawable = math.random(0, 50), texture = 0}, + {component_id = 1, drawable = math.random(0, 50), texture = 0}, + {component_id = 2, drawable = math.random(0, 50), texture = 0}, + {component_id = 3, drawable = math.random(0, 50), texture = 0}, + {component_id = 4, drawable = math.random(0, 50), texture = 0}, + {component_id = 5, drawable = math.random(0, 50), texture = 0}, + {component_id = 6, drawable = math.random(0, 50), texture = 0}, + {component_id = 7, drawable = math.random(0, 50), texture = 0}, + {component_id = 8, drawable = math.random(0, 50), texture = 0}, + {component_id = 9, drawable = math.random(0, 50), texture = 0}, + {component_id = 10, drawable = math.random(0, 50), texture = 0}, + {component_id = 11, drawable = math.random(0, 50), texture = 0}, + }, + props = { + {prop_id = 0, drawable = math.random(0, 50), texture = 0}, + {prop_id = 1, drawable = math.random(0, 50), texture = 0}, + {prop_id = 2, drawable = math.random(0, 50), texture = 0}, + {prop_id = 3, drawable = math.random(0, 50), texture = 0}, + {prop_id = 4, drawable = math.random(0, 50), texture = 0}, + {prop_id = 5, drawable = math.random(0, 50), texture = 0}, + {prop_id = 6, drawable = math.random(0, 50), texture = 0}, + {prop_id = 7, drawable = math.random(0, 50), texture = 0}, + {prop_id = 8, drawable = math.random(0, 50), texture = 0}, + {prop_id = 9, drawable = math.random(0, 50), texture = 0}, + {prop_id = 10, drawable = math.random(0, 50), texture = 0}, + {prop_id = 11, drawable = math.random(0, 50), texture = 0}, + {prop_id = 12, drawable = math.random(0, 50), texture = 0}, + {prop_id = 13, drawable = math.random(0, 50), texture = 0}, + } + }, false, true) +end, false) + + +RegisterCommand('clothing:revert', function(source, args, rawCommand) + local src = source + Clothing.Revert(src) +end, false) + + +RegisterCommand('clothing:current', function(source, args, rawCommand) + local src = source + local currentClothing = Clothing.GetAppearance(src) + if not currentClothing then return end + print(json.encode(currentClothing, { indent = true })) +end, false) + +RegisterCommand('clothing:openmenu', function(source, args, rawCommand) + local src = source + Clothing.OpenMenu(src) +end, false) + + +RegisterCommand('clothing:crowley', function(source, args, rawCommand) + local src = source + Clothing.SetAppearance(src, { + components = { + {drawable = 0, texture = 0, component_id = 0}, + {drawable = 0, texture = 0, component_id = 1}, + {drawable = 19, texture = 0, component_id = 2}, + {drawable = 6, texture = 0, component_id = 3}, + {drawable = 0, texture = 0, component_id = 4}, + {drawable = 0, texture = 0, component_id = 5}, + {drawable = 0, texture = 0, component_id = 6}, + {drawable = 0, texture = 0, component_id = 7}, + {drawable = 23, texture = 0, component_id = 8}, + {drawable = 0, texture = 0, component_id = 9}, + {drawable = 0, texture = 0, component_id = 10}, + {drawable = 4, texture = 2, component_id = 11} + }, + props = { + {drawable = 27, prop_id = 0, texture = 0}, + {drawable = 0, prop_id = 1, texture = 0}, + {drawable = 0, prop_id = 2, texture = 0}, + {drawable = 0, prop_id = 3, texture = 0}, + {drawable = 0, prop_id = 4, texture = 0}, + {drawable = 0, prop_id = 5, texture = 0}, + {drawable = 0, prop_id = 6, texture = 0}, + {drawable = 0, prop_id = 7, texture = 0}, + {drawable = 0, prop_id = 8, texture = 0}, + {drawable = 0, prop_id = 9, texture = 0}, + {drawable = 0, prop_id = 10, texture = 0}, + {drawable = 0, prop_id = 11, texture = 0}, + {drawable = 0, prop_id = 12, texture = 0}, + {drawable = 0, prop_id = 13, texture = 0} + + } + }, false, true) +end, false) diff --git a/modules/clothing/illenium-appearance/shared.lua b/modules/clothing/illenium-appearance/shared.lua new file mode 100644 index 0000000..b295fb6 --- /dev/null +++ b/modules/clothing/illenium-appearance/shared.lua @@ -0,0 +1,222 @@ +-- Get appearence data + +-- { +-- "tattoos": { +-- "ZONE_HAIR": [ +-- { +-- "label": "hair-0-188", +-- "collection": "multiplayer_overlays", +-- "name": "hair-0-188", +-- "hashFemale": "FM_F_Hair_003_c", +-- "hashMale": "FM_M_Hair_003_c", +-- "zone": "ZONE_HAIR" +-- } +-- ] +-- }, +-- "components": [ +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 0 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 1 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 2 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 3 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 4 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 5 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 6 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 7 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 8 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 9 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 10 +-- }, +-- { +-- "texture": -1, +-- "drawable": -1, +-- "component_id": 11 +-- } +-- ], +-- "headBlend": { +-- "skinSecond": 0, +-- "skinMix": 0.0, +-- "shapeFirst": 0, +-- "shapeThird": 0, +-- "skinFirst": 0, +-- "shapeMix": 0.0, +-- "shapeSecond": 0, +-- "skinThird": 0, +-- "thirdMix": 0.0 +-- }, +-- "hair": { +-- "texture": -1, +-- "style": -1, +-- "color": -1, +-- "highlight": -1 +-- }, +-- "eyeColor": -1, +-- "headOverlays": { +-- "lipstick": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "moleAndFreckles": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "ageing": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "makeUp": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "beard": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "blush": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "complexion": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "bodyBlemishes": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "eyebrows": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "chestHair": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "sunDamage": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- }, +-- "blemishes": { +-- "color": 0, +-- "style": 0, +-- "opacity": 0.0, +-- "secondColor": 0 +-- } +-- }, +-- "faceFeatures": { +-- "jawBoneBackSize": 0.0, +-- "noseWidth": 0.0, +-- "eyeBrownHigh": 0.0, +-- "chinBoneSize": 0.0, +-- "chinHole": 0.0, +-- "neckThickness": 0.0, +-- "noseBoneTwist": 0.0, +-- "noseBoneHigh": 0.0, +-- "nosePeakHigh": 0.0, +-- "nosePeakSize": 0.0, +-- "eyesOpening": 0.0, +-- "cheeksBoneHigh": 0.0, +-- "cheeksBoneWidth": 0.0, +-- "cheeksWidth": 0.0, +-- "lipsThickness": 0.0, +-- "nosePeakLowering": 0.0, +-- "jawBoneWidth": 0.0, +-- "eyeBrownForward": 0.0, +-- "chinBoneLenght": 0.0, +-- "chinBoneLowering": 0.0 +-- }, +-- "model": "mp_m_freemode_01", +-- "props": [ +-- { +-- "drawable": -1, +-- "prop_id": 0, +-- "texture": -1 +-- }, +-- { +-- "drawable": -1, +-- "prop_id": 1, +-- "texture": -1 +-- }, +-- { +-- "drawable": -1, +-- "prop_id": 2, +-- "texture": -1 +-- }, +-- { +-- "drawable": -1, +-- "prop_id": 6, +-- "texture": -1 +-- }, +-- { +-- "drawable": -1, +-- "prop_id": 7, +-- "texture": -1 +-- } +-- ] +-- } + +-- this still needed? \ No newline at end of file diff --git a/modules/clothing/qb-clothing/client.lua b/modules/clothing/qb-clothing/client.lua new file mode 100644 index 0000000..45e0d71 --- /dev/null +++ b/modules/clothing/qb-clothing/client.lua @@ -0,0 +1,7 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('qb-clothing') == 'missing' then return end +Clothing = Clothing or {} + +function Clothing.OpenMenu() + TriggerEvent('qb-clothing:client:openMenu') +end \ No newline at end of file diff --git a/modules/clothing/qb-clothing/server.lua b/modules/clothing/qb-clothing/server.lua new file mode 100644 index 0000000..046f84a --- /dev/null +++ b/modules/clothing/qb-clothing/server.lua @@ -0,0 +1,238 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('qb-clothing') == 'missing' then return end +Clothing = Clothing or {} +Clothing.Players = {} + +Callback = Callback or Require("lib/utility/shared/callbacks.lua") +Table = Table or Require('lib/utility/shared/tables.lua') +QBCore = QBCore or exports['qb-core']:GetCoreObject() -- probably easiest for now to call the Framework module + +--- Internal function to get the full appearance data including skin, model, and converted format +---@param src number The server ID of the player +---@return table|nil The player's full appearance data or nil if not found +function Clothing.GetFullAppearanceData(src) + src = src and tonumber(src) + assert(src, "src is nil") + local Player = QBCore.Functions.GetPlayer(src) + if not Player then return end + local citId = Player.PlayerData.citizenid + if not citId then return end + + if Clothing.Players[citId] then return Clothing.Players[citId] end + + local result = MySQL.query.await('SELECT * FROM playerskins WHERE citizenid = ? AND active = ?', { citId, 1 }) + if result[1] == nil then return end + + local model = Player.PlayerData.model + local skinData = json.decode(result[1].skin) + local converted = Clothing.ConvertToDefault(skinData) + + -- Store complete data in the cache + Clothing.Players[citId] = { + model = model, + skin = skinData, + converted = converted + } + + return Clothing.Players[citId] +end + +--- Retrieves a player's converted appearance data for easy use across modules +---@param src number The server ID of the player +---@param fullData boolean Optional - If true, returns the full data object including skin and model +---@return table|nil The player's converted appearance data or full appearance data if fullData=true +function Clothing.GetAppearance(src, fullData) + if fullData then + return Clothing.GetFullAppearanceData(src) + end + local completeData = Clothing.GetFullAppearanceData(src) + if not completeData then return nil end + return completeData.converted +end + +--- Sets a player's appearance based on the provided data +---@param src number The server ID of the player +---@param data table The appearance data to apply +---@param updateBackup boolean Whether to update the backup appearance data +---@return table|nil The updated player appearance data or nil if failed +function Clothing.SetAppearance(src, data, updateBackup, save) + src = src and tonumber(src) + assert(src, "src is nil") + local Player = QBCore.Functions.GetPlayer(src) + if not Player then return end + local citId = Player.PlayerData.citizenid + if not citId then return end + local model = GetEntityModel(GetPlayerPed(src)) + if not model then return end + local converted = Clothing.ConvertFromDefault(data) + + -- Get full appearance data + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + + local currentSkin = currentClothing.skin + for k, v in pairs(converted) do + currentSkin[k] = v + end + + if not Clothing.Players[citId].backup or updateBackup then + Clothing.Players[citId].backup = currentClothing.converted + end + + Clothing.Players[citId] = Clothing.Players[citId] or {} + Clothing.Players[citId].skin = currentSkin + Clothing.Players[citId].model = model + Clothing.Players[citId].converted = Clothing.ConvertToDefault(currentSkin) + if save then + MySQL.update.await('UPDATE playerskins SET skin = ? WHERE citizenid = ? AND active = ?', { + json.encode(currentSkin), + citId, + 1 + }) + end + TriggerClientEvent('community_bridge:client:SetAppearance', src, Clothing.Players[citId].converted) + return Clothing.Players[citId] +end + +--- Sets a player's appearance based on gender-specific data +---@param src number The server ID of the player +---@param data table Table containing separate appearance data for male and female characters +---@return table|nil Appearance updated player appearance data or nil if failed +function Clothing.SetAppearanceExt(src, data) + local tbl = Clothing.IsMale(src) and data.male or data.female + Clothing.SetAppearance(src, tbl) +end + +--- Reverts a player's appearance to their backup appearance +---@param src number The server ID of the player +---@return boolean|nil Returns true if successful or nil if failed +function Clothing.Revert(src) + src = src and tonumber(src) + assert(src, "src is nil") + local currentClothing = Clothing.GetFullAppearanceData(src) + if not currentClothing then return end + local backup = currentClothing.backup + print(src, backup) + if not backup then return end + return Clothing.SetAppearance(src, backup) +end + +function Clothing.OpenMenu(src) + src = src and tonumber(src) + assert(src, "src is nil") + TriggerClientEvent('qb-clothing:client:openMenu', src) +end + +--- Event handler for when a player loads into the server +--- Caches the player's appearance data +AddEventHandler('community_bridge:Server:OnPlayerLoaded', function(src) + src = src and tonumber(src) + assert(src, "src is nil") + local Player = QBCore.Functions.GetPlayer(src) + if not Player then return end + local citId = Player.PlayerData.citizenid + if not citId then return end + + -- Use GetFullAppearanceData to cache the complete appearance + Clothing.GetFullAppearanceData(src) +end) + +--- Event handler for when a player disconnects from the server +--- Removes the player's appearance data from the cache +AddEventHandler('community_bridge:Server:OnPlayerUnload', function(src) + src = src and tonumber(src) + assert(src, "src is nil") + local strSrc = tostring(src) + Clothing.Players[strSrc] = nil +end) + +--- Event handler for when the resource starts +--- Caches appearance data for all currently connected players +AddEventHandler('onResourceStart', function(resource) + if resource ~= GetCurrentResourceName() then return end + for _, playerId in ipairs(GetPlayers()) do + local src = tonumber(playerId) + local strSrc = tostring(src) + if not Clothing.Players[strSrc] then + Clothing.Players[strSrc] = Clothing.GetAppearance(src) + end + end +end) + +--- Callback handler for retrieving a player's appearance data +Callback.Register('community_bridge:cb:GetAppearance', function(source) + local src = source + return Clothing.GetAppearance(src) +end) + +--[[ +RegisterCommand('clothing:debug', function(source, args, rawCommand) + local src = source + Clothing.SetAppearance(src, { + components ={ + {component_id = 1, drawable = math.random(0, 50), texture = 0}, + {component_id = 2, drawable = math.random(0, 50), texture = 0}, + {component_id = 3, drawable = math.random(0, 50), texture = 0}, + {component_id = 4, drawable = math.random(0, 50), texture = 0}, + {component_id = 5, drawable = math.random(0, 50), texture = 0}, + {component_id = 6, drawable = math.random(0, 50), texture = 0}, + {component_id = 7, drawable = math.random(0, 50), texture = 0}, + {component_id = 8, drawable = math.random(0, 50), texture = 0}, + }, + props = { + {prop_id = 3, drawable = 0, texture = 0}, + {prop_id = 1, drawable = 0, texture = 0}, + {prop_id = 2, drawable = 0, texture = 0}, + } + }, false, true) +end, false) + + +RegisterCommand('clothing:revert', function(source, args, rawCommand) + local src = source + Clothing.Revert(src) +end, false) + + +RegisterCommand('clothing:current', function(source, args, rawCommand) + local src = source + local currentClothing = Clothing.GetAppearance(src) + if not currentClothing then return end + print(json.encode(currentClothing, { indent = true })) +end, false) + +RegisterCommand('clothing:openmenu', function(source, args, rawCommand) + local src = source + Clothing.OpenMenu(src) +end, false) +--]] + +-- RegisterCommand('clothing:crowley', function(source, args, rawCommand) +-- local src = source +-- Clothing.SetAppearance(src, { +-- components = { +-- {drawable = 0, texture = 0, component_id = 0}, +-- {drawable = 0, texture = 0, component_id = 1}, +-- {drawable = 19, texture = 0, component_id = 2}, +-- {drawable = 6, texture = 0, component_id = 3}, +-- {drawable = 0, texture = 0, component_id = 4}, +-- {drawable = 0, texture = 0, component_id = 5}, +-- {drawable = 0, texture = 0, component_id = 6}, +-- {drawable = 0, texture = 0, component_id = 7}, +-- {drawable = 23, texture = 0, component_id = 8}, +-- {drawable = 0, texture = 0, component_id = 9}, +-- {drawable = 0, texture = 0, component_id = 10}, +-- {drawable = 4, texture = 2, component_id = 11} +-- }, +-- props = { +-- {drawable = 27, prop_id = 0, texture = 0}, +-- {drawable = 0, prop_id = 1, texture = 0}, +-- {drawable = 0, prop_id = 2, texture = 0}, +-- {drawable = 0, prop_id = 3, texture = 0}, +-- {drawable = 0, prop_id = 4, texture = 0}, +-- {drawable = 0, prop_id = 5, texture = 0}, +-- -- {drawable = 0, prop_id = 6, texture = 0}, +-- -- {drawable = 0, prop_id = 7, texture = 0}, +-- } +-- }, false, true) +-- end, false) \ No newline at end of file diff --git a/modules/clothing/qb-clothing/shared.lua b/modules/clothing/qb-clothing/shared.lua new file mode 100644 index 0000000..7a24b98 --- /dev/null +++ b/modules/clothing/qb-clothing/shared.lua @@ -0,0 +1,201 @@ + +if GetResourceState('qb-clothing') == 'missing' then return end + +Clothing = Clothing or {} + +Components = {} +Components.Map = { + [1] = "mask", + [2] = "hair", + [3] = "arms", + [4] = "pants", + [5] = "bag", + [6] = "shoes", + [7] = "accessory", + [8] = "t-shirt", + [9] = "vest", + [10] = "decals", + [11] = "torso2" +} +Components.InverseMap = { + mask = 1, + hair = 2, + arms = 3, + pants = 4, + bag = 5, + shoes = 6, + accessory = 7, + ['t-shirt'] = 8, --<--I HATE THAT + vest = 9, + decals = 10, + torso2 = 11 +} + +Props = {} +Props.Map = { + [0] = "hat", + [1] = "glass", + [2] = "ear", + [6] = "watch", + [7] = "bracelet" +} +Props.InverseMap = { + hat = 0, + glass = 1, + ear = 2, + watch = 6, + bracelet = 7 +} + +function Components.ConvertFromDefault(defaultComponents) + local returnComponents = {} + for index, componentData in pairs(defaultComponents or {}) do + local componentId = Components.Map[componentData.component_id] + if componentId then + returnComponents[componentId] = { + item = componentData.drawable, + texture = componentData.texture + } + end + end + return returnComponents +end + +function Components.ConvertToDefault(qbComponents) + local returnComponents = {} + for componentIndex, componentData in pairs(qbComponents or {}) do + local componentId = Components.InverseMap[componentIndex] + if componentId then + returnComponents[componentId] = { + component_id = componentId, + drawable = componentData.item, + texture = componentData.texture + } + end + end + return returnComponents +end + +function Props.ConvertFromDefault(defaultProps) + local returnProps = {} + for index, propData in pairs(defaultProps or {}) do + local propId = Props.Map[propData.prop_id] + if propId then + returnProps[propId] = { + item = propData.drawable, + texture = propData.texture + } + end + end + return returnProps +end + +function Props.ConvertToDefault(qbProps) + local returnProps = {} + for propIndex, propData in pairs(qbProps or {}) do + local propId = Props.InverseMap[propIndex] + if propId then + table.insert(returnProps, { + prop_id = propId, + drawable = propData.item, + texture = propData.texture + }) + end + end + table.sort(returnProps, function(a, b) + return a.prop_id < b.prop_id + end) + return returnProps +end + +function Clothing.ConvertFromDefault(defaultClothing) + local components = Components.ConvertFromDefault(defaultClothing.components) + local props = Props.ConvertFromDefault(defaultClothing.props) + + for propsIndex, propData in pairs(props) do + components[propsIndex] = propData + end + + return components --skin +end + +function Clothing.ConvertToDefault(qbClothing) + local components = Components.ConvertToDefault(qbClothing) + local props = Props.ConvertToDefault(qbClothing) + return { components = components, props = props } +end + + + + + + + + + + + + + + + + +-- Clothing = {} + +-- StoredOldClothing = {} + +-- Clothing.SetAppearance = function(clothingData) +-- if GetEntityModel(cache.ped) == `mp_m_freemode_01` then +-- clothingData = clothingData.male +-- else +-- clothingData = clothingData.female +-- end +-- local repackedTable = {} +-- local componentMap = { +-- [1] = "mask", +-- [3] = "arms", +-- [4] = "pants", +-- [5] = "bag", +-- [6] = "shoes", +-- [7] = "accessory", +-- [8] = "t-shirt", +-- [9] = "vest", +-- [10] = "decals", +-- [11] = "torso2" +-- } + +-- local propMap = { +-- [0] = "hat", +-- [1] = "glass", +-- [2] = "ear", +-- [6] = "watch", +-- [7] = "bracelet" +-- } + +-- local specialMap = { +-- eye_color_id = "eye_color", +-- moles_id = "moles", +-- ageing_id = "ageing", +-- hair_id = "hair", +-- face_id = "face" +-- } + +-- for _, data in pairs(clothingData) do +-- if componentMap[data.component_id] then +-- repackedTable[componentMap[data.component_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif propMap[data.prop_id] then +-- repackedTable[propMap[data.prop_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.eye_color_id] then +-- repackedTable[specialMap[data.eye_color_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.moles_id] then +-- repackedTable[specialMap[data.moles_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.ageing_id] then +-- repackedTable[specialMap[data.ageing_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.hair_id] then +-- repackedTable[specialMap[data.hair_id]] = {drawable = data.drawable, texture = data.texture} +-- elseif specialMap[data.face_id] then +-- repackedTable[specialMap[data.face_id]] = {drawable = data.drawable, texture = data.texture} +-- end +-- end +-- TriggerEvent('qb-clothing:client:loadOutfit', repackedTable) +-- end \ No newline at end of file diff --git a/modules/dialogue/_default/client/client.lua b/modules/dialogue/_default/client/client.lua index 1f91e0e..4792b0e 100644 --- a/modules/dialogue/_default/client/client.lua +++ b/modules/dialogue/_default/client/client.lua @@ -36,9 +36,9 @@ function Dialogue.Close(name) end --- Open a dialogue with the player ---- @param name string ---- @param dialogue string ---- @param options table example = {{ id = string, label = string}} +---@param name string +---@param dialogue string +---@param options table example = {{ id = string, label = string}} function Dialogue.Open( name, dialogue, characterOptions, dialogueOptions, onSelected) assert(name, "Name is required") assert(dialogue, "Dialogue is required") @@ -55,26 +55,18 @@ function Dialogue.Open( name, dialogue, characterOptions, dialogueOptions, onSel -- camera magic! if entity then + Wait(500) + local endLocation = GetOffsetFromEntityInWorldCoords(entity, offset.x, offset.y + 2.0, offset.z + 0.5) local pedHeading = GetEntityHeading(entity) - -- Convert heading to radians and calculate offset - local angleRad = math.rad(pedHeading) - local offsetX = math.sin(angleRad) * 1.5 - local offsetY = math.cos(angleRad) * 1.5 - -- Get position in front of ped based on their heading - local endLocation = GetEntityCoords(entity) + vector3(offsetX * offset.x, offsetY * offset.y, 0.5) if not cam then cam = CreateCam("DEFAULT_SCRIPTED_CAMERA", 1) end - local camPos = GetCamCoord(cam) - local dist = #(endLocation - camPos) - local abs = cam and math.abs(dist) - if not abs or abs > 0.5 then - local camAngle = (pedHeading + 180.0) % 360.0 - SetCamRot(cam, rotationOffset.x, rotationOffset.y, camAngle + rotationOffset.z, 2) - SetCamCoord(cam, endLocation.x, endLocation.y, endLocation.z) - RenderScriptCams(true, true, 1000, true, false) - SetCamActive(cam, true) - end + local camAngle = (pedHeading + 180.0) % 360.0 + SetCamRot(cam, rotationOffset.x, rotationOffset.y, camAngle + rotationOffset.z, 2) + SetCamCoord(cam, endLocation.x, endLocation.y, endLocation.z) + RenderScriptCams(true, true, 1000, true, false) + SetCamActive(cam, true) + end SendNUIMessage({ type = "open", @@ -105,62 +97,62 @@ end) -- Debug command if BridgeSharedConfig.DebugLevel >= 1 then - RegisterCommand("dialogue", function() - local pos = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0, 2.0, 0) - local timeout = 500 - local model = `a_f_y_hipster_01` - RequestModel(model) - while not HasModelLoaded(model) do - Wait(0) - timeout = timeout - 1 - if timeout == 0 then - print("Failed to load model") - return - end - end - local ped = CreatePed(0, model, pos.x, pos.y, pos.z, 0.0, false, false) + -- RegisterCommand("dialogue", function() + -- local pos = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0, 2.0, 0) + -- local timeout = 500 + -- local model = `a_f_y_hipster_01` + -- RequestModel(model) + -- while not HasModelLoaded(model) do + -- Wait(0) + -- timeout = timeout - 1 + -- if timeout == 0 then + -- print("Failed to load model") + -- return + -- end + -- end + -- local ped = CreatePed(0, model, pos.x, pos.y, pos.z, 0.0, false, false) - local characterData = { - entity = ped, - offset = vector3(0, 0, 0), - rotationOffset = vector3(0, 0, 0) - } - Wait(750) - Dialogue.Open("Akmed", "Hello how are you doing my friend?", characterData, { - { - label = "Trade with me", - id = 'something', - }, - { - label = "Goodbye", - id = 'someotherthing', - }, - }, - function(selectedId) - if selectedId == 'something' then - Dialogue.Open( "Akmed" , "Thank you for wanting to purchase me lucky charms", characterData, { - { - label = "Fuck off", - id = 'something', - }, - { - label = "Goodbye", - id = 'someotherthing', - }, - }, - function(selectedId) - DeleteEntity(ped) - if selectedId == "something" then - print("You hate lucky charms") - else - print("Thanks for keeping it civil") - end - end) - else - DeleteEntity(ped) - end - end) - end) + -- local characterData = { + -- entity = ped, + -- offset = vector3(0, 0, 0), + -- rotationOffset = vector3(0, 0, 0) + -- } + -- Wait(750) + -- Dialogue.Open("Akmed", "Hello how are you doing my friend?", characterData, { + -- { + -- label = "Trade with me", + -- id = 'something', + -- }, + -- { + -- label = "Goodbye", + -- id = 'someotherthing', + -- }, + -- }, + -- function(selectedId) + -- if selectedId == 'something' then + -- Dialogue.Open( "Akmed" , "Thank you for wanting to purchase me lucky charms", characterData, { + -- { + -- label = "Fuck off", + -- id = 'something', + -- }, + -- { + -- label = "Goodbye", + -- id = 'someotherthing', + -- }, + -- }, + -- function(selectedId) + -- DeleteEntity(ped) + -- if selectedId == "something" then + -- print("You hate lucky charms") + -- else + -- print("Thanks for keeping it civil") + -- end + -- end) + -- else + -- DeleteEntity(ped) + -- end + -- end) + -- end) end return Dialogue \ No newline at end of file diff --git a/modules/dispatch/_default/client/client.lua b/modules/dispatch/_default/client/client.lua index 16f4c99..ab2434e 100644 --- a/modules/dispatch/_default/client/client.lua +++ b/modules/dispatch/_default/client/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field Dispatch = Dispatch or {} ---This will send an alert to currently supported dispatch systems. diff --git a/modules/dispatch/_default/server/server.lua b/modules/dispatch/_default/server/server.lua index 31d76e4..039944b 100644 --- a/modules/dispatch/_default/server/server.lua +++ b/modules/dispatch/_default/server/server.lua @@ -4,10 +4,10 @@ RegisterNetEvent("community_bridge:Server:DispatchAlert", function(data) local jobs = data.jobs for _, name in pairs(jobs) do local activeJobPlayers = Bridge.Framework.GetPlayersByJob(name) - for src, _ in pairs(activeJobPlayers) do + for _, src in pairs(activeJobPlayers) do TriggerClientEvent('community_bridge:Client:DispatchAlert', src, data) end end end) -return Dispatch \ No newline at end of file +return Dispatch diff --git a/modules/dispatch/bub_mdt/client/client.lua b/modules/dispatch/bub-mdt/client/client.lua similarity index 84% rename from modules/dispatch/bub_mdt/client/client.lua rename to modules/dispatch/bub-mdt/client/client.lua index f5850f2..a17f3f5 100644 --- a/modules/dispatch/bub_mdt/client/client.lua +++ b/modules/dispatch/bub-mdt/client/client.lua @@ -1,4 +1,5 @@ -if GetResourceState('bub-mdt') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('bub-mdt') == 'missing' then return end Dispatch = Dispatch or {} Dispatch.SendAlert = function(data) diff --git a/modules/dispatch/bub-mdt/server/server.lua b/modules/dispatch/bub-mdt/server/server.lua new file mode 100644 index 0000000..a95dfde --- /dev/null +++ b/modules/dispatch/bub-mdt/server/server.lua @@ -0,0 +1,4 @@ +if GetResourceState('bub-mdt') == 'missing' then return end +Dispatch = Dispatch or {} + +return Dispatch \ No newline at end of file diff --git a/modules/dispatch/bub_mdt/server/server.lua b/modules/dispatch/bub_mdt/server/server.lua deleted file mode 100644 index 60cd14c..0000000 --- a/modules/dispatch/bub_mdt/server/server.lua +++ /dev/null @@ -1,4 +0,0 @@ -if GetResourceState('bub-mdt') ~= 'started' then return end -Dispatch = Dispatch or {} - -return Dispatch \ No newline at end of file diff --git a/modules/dispatch/cd_dispatch/client/client.lua b/modules/dispatch/cd_dispatch/client/client.lua index c37ff1e..799b1fe 100644 --- a/modules/dispatch/cd_dispatch/client/client.lua +++ b/modules/dispatch/cd_dispatch/client/client.lua @@ -1,4 +1,5 @@ -if GetResourceState('cd_dispatch') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('cd_dispatch') == 'missing' then return end Dispatch = Dispatch or {} Dispatch.SendAlert = function(data) diff --git a/modules/dispatch/cd_dispatch/server/server.lua b/modules/dispatch/cd_dispatch/server/server.lua index 20f62c3..856546e 100644 --- a/modules/dispatch/cd_dispatch/server/server.lua +++ b/modules/dispatch/cd_dispatch/server/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('cd_dispatch') ~= 'started' then return end +if GetResourceState('cd_dispatch') == 'missing' then return end Dispatch = Dispatch or {} return Dispatch \ No newline at end of file diff --git a/modules/dispatch/lb-tablet/client/client.lua b/modules/dispatch/lb-tablet/client/client.lua index 28483ab..c8aa413 100644 --- a/modules/dispatch/lb-tablet/client/client.lua +++ b/modules/dispatch/lb-tablet/client/client.lua @@ -1,4 +1,5 @@ -if GetResourceState('lb-tablet') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('lb-tablet') == 'missing' then return end Dispatch = Dispatch or {} local function getPriorityLevel(priority) @@ -13,7 +14,7 @@ local function getPriorityLevel(priority) end end ----commentThis will send an alert to the passed jobs +---This will send an alert to the passed jobs ---@param data table Dispatch.SendAlert = function(data) local streetName, _ = Utility.GetStreetNameAtCoords(data.coords) diff --git a/modules/dispatch/lb-tablet/server/server.lua b/modules/dispatch/lb-tablet/server/server.lua index b4806d8..e23d4b4 100644 --- a/modules/dispatch/lb-tablet/server/server.lua +++ b/modules/dispatch/lb-tablet/server/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('lb-tablet') ~= 'started' then return end +if GetResourceState('lb-tablet') == 'missing' then return end Dispatch = Dispatch or {} RegisterNetEvent("community_bridge:server:dispatch:sendAlert", function(data) diff --git a/modules/dispatch/linden_outlawalert/client/client.lua b/modules/dispatch/linden_outlawalert/client/client.lua index eed7de0..4b63501 100644 --- a/modules/dispatch/linden_outlawalert/client/client.lua +++ b/modules/dispatch/linden_outlawalert/client/client.lua @@ -1,4 +1,5 @@ -if GetResourceState('linden_outlawalert') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('linden_outlawalert') == 'missing' then return end Dispatch = Dispatch or {} Dispatch.SendAlert = function(data) diff --git a/modules/dispatch/linden_outlawalert/server/server.lua b/modules/dispatch/linden_outlawalert/server/server.lua index 4e58535..d8d9fd6 100644 --- a/modules/dispatch/linden_outlawalert/server/server.lua +++ b/modules/dispatch/linden_outlawalert/server/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('linden_outlawalert') ~= 'started' then return end +if GetResourceState('linden_outlawalert') == 'missing' then return end Dispatch = Dispatch or {} return Dispatch \ No newline at end of file diff --git a/modules/dispatch/ps-dispatch/client/client.lua b/modules/dispatch/ps-dispatch/client/client.lua index a4eb7d8..835fcea 100644 --- a/modules/dispatch/ps-dispatch/client/client.lua +++ b/modules/dispatch/ps-dispatch/client/client.lua @@ -1,4 +1,5 @@ -if GetResourceState('ps-dispatch') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('ps-dispatch') == 'missing' then return end if GetResourceState('lb-tablet') == 'started' then return end Dispatch = Dispatch or {} diff --git a/modules/dispatch/ps-dispatch/server/server.lua b/modules/dispatch/ps-dispatch/server/server.lua index dde11f4..b60c698 100644 --- a/modules/dispatch/ps-dispatch/server/server.lua +++ b/modules/dispatch/ps-dispatch/server/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('ps-dispatch') ~= 'started' then return end +if GetResourceState('ps-dispatch') == 'missing' then return end if GetResourceState('lb-tablet') == 'started' then return end Dispatch = Dispatch or {} diff --git a/modules/dispatch/qs_dispatch/client/client.lua b/modules/dispatch/qs_dispatch/client/client.lua index f68f798..3762ddc 100644 --- a/modules/dispatch/qs_dispatch/client/client.lua +++ b/modules/dispatch/qs_dispatch/client/client.lua @@ -1,4 +1,5 @@ -if GetResourceState('qs-dispatch') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('qs-dispatch') == 'missing' then return end Dispatch = Dispatch or {} Dispatch.SendAlert = function(data) diff --git a/modules/dispatch/qs_dispatch/server/server.lua b/modules/dispatch/qs_dispatch/server/server.lua index 46fa79a..ae08560 100644 --- a/modules/dispatch/qs_dispatch/server/server.lua +++ b/modules/dispatch/qs_dispatch/server/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('qs-dispatch') ~= 'started' then return end +if GetResourceState('qs-dispatch') == 'missing' then return end Dispatch = Dispatch or {} return Dispatch \ No newline at end of file diff --git a/modules/dispatch/redutzu-mdt/client/client.lua b/modules/dispatch/redutzu-mdt/client/client.lua index 895de7b..8b0ef79 100644 --- a/modules/dispatch/redutzu-mdt/client/client.lua +++ b/modules/dispatch/redutzu-mdt/client/client.lua @@ -1,4 +1,5 @@ -if GetResourceState('redutzu-mdt') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('redutzu-mdt') == 'missing' then return end Dispatch = Dispatch or {} Dispatch.SendAlert = function(data) diff --git a/modules/dispatch/redutzu-mdt/server/server.lua b/modules/dispatch/redutzu-mdt/server/server.lua index ea72477..c1c0ac0 100644 --- a/modules/dispatch/redutzu-mdt/server/server.lua +++ b/modules/dispatch/redutzu-mdt/server/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('redutzu-mdt') ~= 'started' then return end +if GetResourceState('redutzu-mdt') == 'missing' then return end Dispatch = Dispatch or {} RegisterNetEvent("community_bridge:server:dispatch:sendAlert", function(data) diff --git a/modules/dispatch/tk_dispatch/client/client.lua b/modules/dispatch/tk_dispatch/client/client.lua index edfa708..61de466 100644 --- a/modules/dispatch/tk_dispatch/client/client.lua +++ b/modules/dispatch/tk_dispatch/client/client.lua @@ -1,4 +1,5 @@ -if GetResourceState('tk_dispatch') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('tk_dispatch') == 'missing' then return end Dispatch = Dispatch or {} Dispatch.SendAlert = function(data) diff --git a/modules/dispatch/tk_dispatch/server/server.lua b/modules/dispatch/tk_dispatch/server/server.lua index 688895d..aeeb8dc 100644 --- a/modules/dispatch/tk_dispatch/server/server.lua +++ b/modules/dispatch/tk_dispatch/server/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('tk_dispatch') ~= 'started' then return end +if GetResourceState('tk_dispatch') == 'missing' then return end Dispatch = Dispatch or {} return Dispatch \ No newline at end of file diff --git a/modules/doorlock/_default/client.lua b/modules/doorlock/_default/client.lua new file mode 100644 index 0000000..9743a7d --- /dev/null +++ b/modules/doorlock/_default/client.lua @@ -0,0 +1,10 @@ +---@diagnostic disable: duplicate-set-field +Doorlock = Doorlock or {} + +---This will get the closest door to the ped +---@return string | nil +Doorlock.GetClosestDoor = function() + return nil +end + +return Doorlock \ No newline at end of file diff --git a/modules/doorlock/_default/server.lua b/modules/doorlock/_default/server.lua new file mode 100644 index 0000000..882615b --- /dev/null +++ b/modules/doorlock/_default/server.lua @@ -0,0 +1,13 @@ +---@diagnostic disable: duplicate-set-field + +Doorlock = Doorlock or {} + +---This will toggle the lock status of the door. +---@param doorID string +---@param toggle boolean +---@return boolean +Doorlock.ToggleDoorLock = function(doorID, toggle) + return true +end + +return Doorlock \ No newline at end of file diff --git a/modules/doorlock/doors_creator/client.lua b/modules/doorlock/doors_creator/client.lua index 26a691b..d4da080 100644 --- a/modules/doorlock/doors_creator/client.lua +++ b/modules/doorlock/doors_creator/client.lua @@ -1,5 +1,5 @@ ---@diagnostic disable: duplicate-set-field -if GetResourceState('doors_creator') ~= 'started' then return end +if GetResourceState('doors_creator') == 'missing' then return end Doorlock = Doorlock or {} diff --git a/modules/doorlock/doors_creator/server.lua b/modules/doorlock/doors_creator/server.lua index ed9a0b1..89223e8 100644 --- a/modules/doorlock/doors_creator/server.lua +++ b/modules/doorlock/doors_creator/server.lua @@ -1,5 +1,5 @@ ---@diagnostic disable: duplicate-set-field -if GetResourceState('doors_creator') ~= 'started' then return end +if GetResourceState('doors_creator') == 'missing' then return end Doorlock = Doorlock or {} diff --git a/modules/doorlock/ox_doorlock/client.lua b/modules/doorlock/ox_doorlock/client.lua index 04a2d31..fc35fa0 100644 --- a/modules/doorlock/ox_doorlock/client.lua +++ b/modules/doorlock/ox_doorlock/client.lua @@ -1,5 +1,5 @@ ---@diagnostic disable: duplicate-set-field -if GetResourceState('ox_doorlock') ~= 'started' then return end +if GetResourceState('ox_doorlock') == 'missing' then return end Doorlock = Doorlock or {} diff --git a/modules/doorlock/ox_doorlock/server.lua b/modules/doorlock/ox_doorlock/server.lua index 132efa1..739751d 100644 --- a/modules/doorlock/ox_doorlock/server.lua +++ b/modules/doorlock/ox_doorlock/server.lua @@ -1,5 +1,5 @@ ---@diagnostic disable: duplicate-set-field -if GetResourceState('ox_doorlock') ~= 'started' then return end +if GetResourceState('ox_doorlock') == 'missing' then return end Doorlock = Doorlock or {} diff --git a/modules/doorlock/qb-doorlock/client.lua b/modules/doorlock/qb-doorlock/client.lua index b5275b9..c21442b 100644 --- a/modules/doorlock/qb-doorlock/client.lua +++ b/modules/doorlock/qb-doorlock/client.lua @@ -1,5 +1,5 @@ ---@diagnostic disable: duplicate-set-field -if GetResourceState('qb-doorlock') ~= 'started' then return end +if GetResourceState('qb-doorlock') == 'missing' then return end Doorlock = Doorlock or {} diff --git a/modules/doorlock/qb-doorlock/server.lua b/modules/doorlock/qb-doorlock/server.lua index 5fd74c9..a88a9b9 100644 --- a/modules/doorlock/qb-doorlock/server.lua +++ b/modules/doorlock/qb-doorlock/server.lua @@ -1,5 +1,5 @@ ---@diagnostic disable: duplicate-set-field -if GetResourceState('qb-doorlock') ~= 'started' then return end +if GetResourceState('qb-doorlock') == 'missing' then return end Doorlock = Doorlock or {} diff --git a/modules/doorlock/rcore_doorlock/client.lua b/modules/doorlock/rcore_doorlock/client.lua index 11860b1..06e5a7d 100644 --- a/modules/doorlock/rcore_doorlock/client.lua +++ b/modules/doorlock/rcore_doorlock/client.lua @@ -1,5 +1,5 @@ ---@diagnostic disable: duplicate-set-field -if GetResourceState('rcore_doorlock') ~= 'started' then return end +if GetResourceState('rcore_doorlock') == 'missing' then return end Doorlock = Doorlock or {} diff --git a/modules/doorlock/rcore_doorlock/server.lua b/modules/doorlock/rcore_doorlock/server.lua index 016f952..176e23e 100644 --- a/modules/doorlock/rcore_doorlock/server.lua +++ b/modules/doorlock/rcore_doorlock/server.lua @@ -1,5 +1,5 @@ ---@diagnostic disable: duplicate-set-field -if GetResourceState('rcore_doorlock') ~= 'started' then return end +if GetResourceState('rcore_doorlock') == 'missing' then return end Doorlock = Doorlock or {} diff --git a/modules/framework/es_extended/client.lua b/modules/framework/es_extended/client.lua index e2838a9..7b42719 100644 --- a/modules/framework/es_extended/client.lua +++ b/modules/framework/es_extended/client.lua @@ -5,11 +5,14 @@ ESX = exports["es_extended"]:getSharedObject() Framework = Framework or {} +---This will get the name of the framework being used (if a supported framework). +---@return string Framework.GetFrameworkName = function() return 'es_extended' end ----This will return a table of the players data, this is an internal table and should not be used. +---This will return a table of the player data, this will be in the framework format. +---This is mainly for internal bridge use and should be avoided. ---@return table Framework.GetPlayerData = function() return ESX.GetPlayerData() @@ -32,13 +35,13 @@ Framework.GetPlayerDob = function() end ---This will return the players metadata for the specified metadata key. ----@param metadata string ----@return table | nil +---@param metadata table | string +---@return table | string | number | boolean Framework.GetPlayerMetaData = function(metadata) return Framework.GetPlayerData().metadata[metadata] end ----This will prompt the user with a notification message +---This will send a notification to the player. ---@param message string ---@param type string ---@param time number @@ -61,14 +64,14 @@ Framework.HideHelpText = function() return exports['esx_textui']:HideUI() end ----This will return the players identifier +---This will get the players identifier (citizenid) etc. ---@return string Framework.GetPlayerIdentifier = function() local playerData = Framework.GetPlayerData() return playerData.identifier end ----This will return the players first name, and the last name +---This will get the players name (first and last). ---@return string ---@return string Framework.GetPlayerName = function() @@ -103,7 +106,7 @@ Framework.GetPlayerJobData = function() } end ----This will return a boolean if the player has the item in their inventory +---This will return if the player has the specified item in their inventory. ---@param item string ---@return boolean Framework.HasItem = function(item) @@ -111,6 +114,15 @@ Framework.HasItem = function(item) return hasItem > 0 and true or false end +---This will return the item count for the specified item in the players inventory. +---@param item string +---@return number +Framework.GetItemCount = function(item) + local inventory = Framework.GetPlayerInventory() + if not inventory then return 0 end + return inventory[item].count or 0 +end + ---This will return a table of the players inventory ---@return table Framework.GetPlayerInventory = function() @@ -118,16 +130,38 @@ Framework.GetPlayerInventory = function() return playerData.inventory end ----This will return a number of the item in the players inventory ----@param item string ----@return number -Framework.GetItemCount = function(item) - local inventory = Framework.GetPlayerInventory() - if not inventory then return 0 end - return inventory[item].count or 0 +---This will return the vehicle properties for the specified vehicle. +---@param vehicle number +---@return table +Framework.GetVehicleProperties = function(vehicle) + if not vehicle or not DoesEntityExist(vehicle) then return {} end + local vehicleProps = ESX.Game.GetVehicleProperties(vehicle) + return vehicleProps or {} end ----This will return a boolean if the player is dead +---This will set the vehicle properties for the specified vehicle. +---@param vehicle number +---@param properties table +---@return boolean +Framework.SetVehicleProperties = function(vehicle, properties) + if not vehicle or not DoesEntityExist(vehicle) then return false end + if not properties then return false end + if NetworkGetEntityIsNetworked(vehicle) then + local vehNetID = NetworkGetNetworkIdFromEntity(vehicle) + local entOwner = GetPlayerServerId(NetworkGetEntityOwner(vehNetID)) + if entOwner ~= GetPlayerServerId(PlayerId()) then + NetworkRequestControlOfEntity(vehicle) + local count = 0 + while not NetworkHasControlOfEntity(vehicle) and count < 3000 do + Wait(1) + count = count + 1 + end + end + end + return true, QBCore.Functions.SetVehicleProperties(vehicle, properties) +end + +---This will get a players dead status. ---@return boolean Framework.GetIsPlayerDead = function() local playerData = Framework.GetPlayerData() diff --git a/modules/framework/es_extended/server.lua b/modules/framework/es_extended/server.lua index 780b20f..8ab3843 100644 --- a/modules/framework/es_extended/server.lua +++ b/modules/framework/es_extended/server.lua @@ -1,15 +1,32 @@ ---@diagnostic disable: duplicate-set-field if GetResourceState('es_extended') ~= 'started' then return end + Prints = Prints or Require("lib/utility/shared/prints.lua") ESX = exports["es_extended"]:getSharedObject() Framework = Framework or {} +---This will return the name of the framework in use. +---@return string Framework.GetFrameworkName = function() return 'es_extended' end +---This will return if the player is an admin in the framework. +---@param src any +---@return boolean +Framework.GetIsFrameworkAdmin = function(src) + if not src then return false end + local xPlayer = Framework.GetPlayer(src) + if not xPlayer then return false end + local group = xPlayer.getGroup() + if group == 'admin' or group == 'superadmin' then return true end + return false +end + +---This will get the players birth date +---@return string|nil Framework.GetPlayerDob = function(src) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -17,9 +34,7 @@ Framework.GetPlayerDob = function(src) return dob end ---- This will return a table of the players data ---- ---- This table is in the framework format and not converted to any standard. +--- Returns the player data of the specified source in the framework defualt format. ---@param src any ---@return table | nil Framework.GetPlayer = function(src) @@ -30,18 +45,24 @@ end -- Framework.GetPlayerIdentifier(src) -- Returns the citizen ID of the player. +---@param src number +---@return string | nil Framework.GetPlayerIdentifier = function(src) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end return xPlayer.getIdentifier() end +---This will return the jobs registered in the framework in a table. +---Format of the table is: +---{name = jobName, label = jobLabel, grade = {name = gradeName, level = gradeLevel}} +---@return table Framework.GetFrameworkJobs = function() return ESX.GetJobs() end - -- Framework.GetPlayerName(src) -- Returns the first and last name of the player. +---@return string|nil, string|nil Framework.GetPlayerName = function(src) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -59,9 +80,12 @@ Framework.GetPlayers = function() return playerList end --- Framework.GetItem(src, item, metadata) --- Returns a table of items matching the specified name and if passed metadata from the player's inventory. --- returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot} +---Returns a table of items matching the specified name and if passed metadata from the player's inventory. +---returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot} +---@param src number +---@param item string +---@param _ table +---@return table|nil Framework.GetItem = function(src, item, _) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -80,15 +104,19 @@ Framework.GetItem = function(src, item, _) return repackedTable end --- Framework.GetItemCount(src, item, _) --- Returns the count of items matching the specified name and if passed metadata from the player's inventory. +---This will return the count of the item in the players inventory, if not found will return 0. +---if metadata is passed it will find the matching items count (esx_core does not feature metadata items). +---@param src number +---@param item string +---@param _ table +---@return number Framework.GetItemCount = function(src, item, _) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end return xPlayer.getInventoryItem(item).count end ----comment +---This will return a boolean if the player has the item. ---@param src number ---@param item string ---@return boolean @@ -99,7 +127,9 @@ end -- Framework.GetPlayerInventory(src) -- Returns the entire inventory of the player as a table. --- returns {name = v.name, count = v.amount, _, _} +-- returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot} +---@param src number +---@return table | nil Framework.GetPlayerInventory = function(src) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -120,6 +150,7 @@ end -- Framework.SetMetadata(src, metadata, value) -- Adds the specified metadata key and number value to the player's data. +---@return boolean|nil Framework.SetPlayerMetadata = function(src, metadata, value) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -128,7 +159,10 @@ Framework.SetPlayerMetadata = function(src, metadata, value) end -- Framework.GetMetadata(src, metadata) --- Gets the specified metadata key and value to the player's data. +-- Gets the specified metadata key to the player's data. +---@param src number +---@param metadata string +---@return any|nil Framework.GetPlayerMetadata = function(src, metadata) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -146,12 +180,18 @@ Framework.GetStatus = function(src, column) return xPlayer.get(column) or nil end +---This will return a boolean if the player is dead or in last stand. +---@param src number +---@return boolean|nil Framework.GetIsPlayerDead = function(src) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end return xPlayer.get("is_dead") or false end +---This will revive a player, if the player is dead or in last stand. +---@param src number +---@return boolean Framework.RevivePlayer = function(src) src = tonumber(src) if not src then return false end @@ -161,6 +201,9 @@ end -- Framework.AddThirst(src, value) -- Adds the specified value from the player's thirst level. +---@param src number +---@param value number +---@return number | nil Framework.AddThirst = function(src, value) local clampIT = Math.Clamp(value, 0, 200000) local levelForEsx = clampIT * 2000 @@ -170,6 +213,9 @@ end -- Framework.AddHunger(src, value) -- Adds the specified value from the player's hunger level. +---@param src number +---@param value number +---@return number | nil Framework.AddHunger = function(src, value) local clampIT = Math.Clamp(value, 0, 200000) local levelForEsx = clampIT * 2000 @@ -177,12 +223,18 @@ Framework.AddHunger = function(src, value) return levelForEsx end +---This will get the hunger of a player +---@param src number +---@return number | nil Framework.GetHunger = function(src) local status = Framework.GetStatus(src, "status") if not status then return 0 end return status.hunger end +---This will get the thirst of a player +---@param src any +---@return number | nil Framework.GetThirst = function(src) local status = Framework.GetStatus(src, "status") if not status then return 0 end @@ -191,6 +243,8 @@ end -- Framework.GetPlayerPhone(src) -- Returns the phone number of the player. +---@param src number +---@return string | nil Framework.GetPlayerPhone = function(src) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -241,9 +295,9 @@ Framework.GetPlayerDuty = function(src) return true end ----Sets the players duty status. +---This will toggle a players duty status ---@param src number ----@param dutystatus boolean +---@param status boolean ---@return boolean Framework.SetPlayerDuty = function(src, dutystatus) local xPlayer = Framework.GetPlayer(src) @@ -253,22 +307,26 @@ Framework.SetPlayerDuty = function(src, dutystatus) return xPlayer.setJob(job.name, job.grade, dutystatus) end --- Framework.GetPlayersByJob(jobname) --- returns a table of player sources that have the specified job name. +---This will get a table of player sources that have the specified job name. +---@param job any +---@return table Framework.GetPlayersByJob = function(job) local players = GetPlayers() local playerList = {} for _, src in pairs(players) do local xPlayer = Framework.GetPlayer(src) - if xPlayer.getJob().name == job then + if xPlayer and xPlayer.getJob().name == job then table.insert(playerList, src) end end return playerList end --- Framework.SetPlayerJob(src, name, grade) -- Sets the player's job to the specified name and grade. +---@param src number +---@param name string +---@param grade string +---@return nil Framework.SetPlayerJob = function(src, name, grade) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -279,8 +337,11 @@ Framework.SetPlayerJob = function(src, name, grade) return xPlayer.setJob(name, grade, true) end --- Framework.AddAccountBalance(src, _type, amount) --- Adds the specified amount to the player's account balance of the specified type. +---This will add money based on the type of account (money/bank) +---@param src number +---@param _type string +---@param amount number +---@return boolean | nil Framework.AddAccountBalance = function(src, _type, amount) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -288,8 +349,11 @@ Framework.AddAccountBalance = function(src, _type, amount) return xPlayer.addAccountMoney(_type, amount) end --- Framework.RemoveAccountBalance(src, _type, amount) --- Removes the specified amount from the player's account balance of the specified type. +---This will remove money based on the type of account (money/bank) +---@param src number +---@param _type string +---@param amount number +---@return boolean | nil Framework.RemoveAccountBalance = function(src, _type, amount) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -298,8 +362,10 @@ Framework.RemoveAccountBalance = function(src, _type, amount) return true end --- Framework.GetAccountBalance(src, _type) --- Returns the player's account balance of the specified type. +---This will remove money based on the type of account (money/bank) +---@param src number +---@param _type string +---@return string | nil Framework.GetAccountBalance = function(src, _type) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end @@ -307,22 +373,37 @@ Framework.GetAccountBalance = function(src, _type) return xPlayer.getAccount(_type).money end --- Framework.AddItem(src, item, amount, _, _) +-- Framework.AddItem(src, item, amount, slot, metadata) -- Adds the specified item to the player's inventory. +---@param src number +---@param item string +---@param amount number +---@param slot number +---@param metadata table +---@return boolean | nil Framework.AddItem = function(src, item, amount, slot, metadata) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end return xPlayer.addInventoryItem(item, amount) end --- Framework.RemoveItem(src, item, amount, _, _) +-- Framework.RemoveItem(src, item, amount, slot, metadata) -- Removes the specified item from the player's inventory. +---@param src number +---@param item string +---@param amount number +---@param slot number +---@param metadata table +---@return boolean | nil Framework.RemoveItem = function(src, item, amount, slot, metadata) local xPlayer = Framework.GetPlayer(src) if not xPlayer then return end return xPlayer.removeInventoryItem(item, amount) end +---This will get all owned vehicles for the player +---@param src number +---@return table Framework.GetOwnedVehicles = function(src) local citizenId = Framework.GetPlayerIdentifier(src) local result = MySQL.Sync.fetchAll("SELECT vehicle, plate FROM owned_vehicles WHERE owner = '" .. citizenId .. "'") @@ -336,8 +417,11 @@ Framework.GetOwnedVehicles = function(src) return vehicles end + -- Framework.RegisterUsableItem(item, cb) -- Registers a usable item with a callback function. +---@param itemName string +---@param cb function Framework.RegisterUsableItem = function(itemName, cb) local func = function(src, item, itemData) itemData = itemData or item @@ -348,13 +432,13 @@ Framework.RegisterUsableItem = function(itemName, cb) ESX.RegisterUsableItem(itemName, func) end -RegisterNetEvent("esx:playerLoaded", function() - local src = source +RegisterNetEvent("esx:playerLoaded", function(src) + src = src or source TriggerEvent("community_bridge:Server:OnPlayerLoaded", src) end) -RegisterNetEvent("esx:playerLogout", function() - local src = source +RegisterNetEvent("esx:playerLogout", function(src) + src = src or source TriggerEvent("community_bridge:Server:OnPlayerUnload", src) end) diff --git a/modules/framework/qb-core/client.lua b/modules/framework/qb-core/client.lua index 8686657..be6e3f9 100644 --- a/modules/framework/qb-core/client.lua +++ b/modules/framework/qb-core/client.lua @@ -2,9 +2,11 @@ if GetResourceState('qb-core') ~= 'started' then return end if GetResourceState('qbx_core') == 'started' then return end +Framework = Framework or {} + QBCore = exports['qb-core']:GetCoreObject() -Framework = Framework or {} +Framework.Shared = QBCore.Shared ---This will get the name of the framework being used (if a supported framework). ---@return string @@ -12,6 +14,9 @@ Framework.GetFrameworkName = function() return 'qb-core' end +---This will return a table of the player data, this will be in the framework format. +---This is mainly for internal bridge use and should be avoided. +---@return table Framework.GetPlayerData = function() return QBCore.Functions.GetPlayerData() end @@ -45,6 +50,11 @@ Framework.GetPlayerMetaData = function(metadata) return Framework.GetPlayerData().metadata[metadata] end +---This will send a notification to the player. +---@param message string +---@param type string +---@param time number +---@return nil Framework.Notify = function(message, type, time) TriggerEvent('QBCore:Notify', message, 'primary', time) end @@ -63,6 +73,9 @@ Framework.HideHelpText = function() return exports['qb-core']:HideText() end +---This will return the item data for the specified item. +---@param item string +---@return table Framework.GetItemInfo = function(item) local itemData = QBCore.Shared.Items[item] if not itemData then return {} end @@ -117,11 +130,14 @@ Framework.GetPlayerJobData = function() } end +---This will return if the player has the specified item in their inventory. +---@param item string +---@return boolean Framework.HasItem = function(item) return QBCore.Functions.HasItem(item) end ----comment +---This will return the item count for the specified item in the players inventory. ---@param item string ---@return number Framework.GetItemCount = function(item) @@ -135,6 +151,8 @@ Framework.GetItemCount = function(item) return count end +---This will return the players inventory as a table in the ox_inventory style flormat. +---@return table Framework.GetPlayerInventory = function() local items = {} local frameworkInv = Framework.GetPlayerData().items @@ -153,6 +171,37 @@ Framework.GetPlayerInventory = function() return items end +---This will return the vehicle properties for the specified vehicle. +---@param vehicle number +---@return table +Framework.GetVehicleProperties = function(vehicle) + if not vehicle or not DoesEntityExist(vehicle) then return {} end + local vehicleProps = QBCore.Functions.GetVehicleProperties(vehicle) + return vehicleProps or {} +end + +---This will set the vehicle properties for the specified vehicle. +---@param vehicle number +---@param properties table +---@return boolean +Framework.SetVehicleProperties = function(vehicle, properties) + if not vehicle or not DoesEntityExist(vehicle) then return false end + if not properties then return false end + if NetworkGetEntityIsNetworked(vehicle) then + local vehNetID = NetworkGetNetworkIdFromEntity(vehicle) + local entOwner = GetPlayerServerId(NetworkGetEntityOwner(vehNetID)) + if entOwner ~= GetPlayerServerId(PlayerId()) then + NetworkRequestControlOfEntity(vehicle) + local count = 0 + while not NetworkHasControlOfEntity(vehicle) and count < 3000 do + Wait(1) + count = count + 1 + end + end + end + return true, QBCore.Functions.SetVehicleProperties(vehicle, properties) +end + ---This will get a players dead status. ---@return boolean Framework.GetIsPlayerDead = function() @@ -160,8 +209,6 @@ Framework.GetIsPlayerDead = function() return playerData.metadata["isdead"] or playerData.metadata["inlaststand"] end -Framework.Shared = QBCore.Shared - RegisterNetEvent('QBCore:Client:OnPlayerLoaded', function() Wait(1500) TriggerEvent('community_bridge:Client:OnPlayerLoaded') diff --git a/modules/framework/qb-core/server.lua b/modules/framework/qb-core/server.lua index 9885980..95f71b7 100644 --- a/modules/framework/qb-core/server.lua +++ b/modules/framework/qb-core/server.lua @@ -2,16 +2,30 @@ if GetResourceState('qb-core') ~= 'started' then return end if GetResourceState('qbx_core') == 'started' then return end +Framework = Framework or {} + QBCore = exports['qb-core']:GetCoreObject() -Framework = Framework or {} Framework.Shared = QBCore.Shared + +---This will return the name of the framework in use. +---@return string Framework.GetFrameworkName = function() return 'qb-core' end +---This will return if the player is an admin in the framework. +---@param src any +---@return boolean +Framework.GetIsFrameworkAdmin = function(src) + if not src then return false end + return QBCore.Functions.HasPermission(src, 'admin') +end + -- Framework.GetPlayerIdentifier(src) -- Returns the citizen ID of the player. +---@param src number +---@return string | nil Framework.GetPlayerIdentifier = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -19,7 +33,7 @@ Framework.GetPlayerIdentifier = function(src) return playerData.citizenid end ---- Returns the player data of the specified source. +--- Returns the player data of the specified source in the framework defualt format. ---@param src any ---@return table | nil Framework.GetPlayer = function(src) @@ -28,6 +42,10 @@ Framework.GetPlayer = function(src) return player end +---This will return the jobs registered in the framework in a table. +---Format of the table is: +---{name = jobName, label = jobLabel, grade = {name = gradeName, level = gradeLevel}} +---@return table Framework.GetFrameworkJobs = function() local jobs = {} for k, v in pairs(QBCore.Shared.Jobs) do @@ -42,7 +60,7 @@ end -- Framework.GetPlayerName(src) -- Returns the first and last name of the player. ----@return string, string +---@return string|nil, string|nil Framework.GetPlayerName = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -50,8 +68,9 @@ Framework.GetPlayerName = function(src) return playerData.charinfo.firstname, playerData.charinfo.lastname end ----This will get the players birth date ----@return string +---Returns the player date of birth. +---@param src number +---@return string|nil Framework.GetPlayerDob = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -59,9 +78,12 @@ Framework.GetPlayerDob = function(src) return playerData.charinfo.birthdate end --- Framework.GetItem(src, item, metadata) --- Returns a table of items matching the specified name and if passed metadata from the player's inventory. --- returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot} +---Returns a table of items matching the specified name and if passed metadata from the player's inventory. +---returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot} +---@param src number +---@param item string +---@param metadata table +---@return table|nil Framework.GetItem = function(src, item, metadata) local player = Framework.GetPlayer(src) if not player then return end @@ -107,7 +129,7 @@ end ---@return number Framework.GetItemCount = function(src, item, metadata) local player = Framework.GetPlayer(src) - if not player then return end + if not player then return 0 end local playerData = player.PlayerData local playerInventory = playerData.items local count = 0 @@ -131,6 +153,8 @@ end -- Framework.GetPlayerInventory(src) -- Returns the entire inventory of the player as a table. -- returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot} +---@param src number +---@return table | nil Framework.GetPlayerInventory = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -159,6 +183,11 @@ Framework.GetPlayers = function() return playerList end +---This will return the item data for the specified slot. +---Format {name, label, weight, count, metadata, slot, stack, description} +---@param src number +---@param slot number +---@return table|nil Framework.GetItemBySlot = function(src, slot) local player = Framework.GetPlayer(src) if not player then return end @@ -184,7 +213,7 @@ end -- Framework.SetMetadata(src, metadata, value) -- Adds the specified metadata key and number value to the player's data. ----@return boolean | nil +---@return boolean|nil Framework.SetPlayerMetadata = function(src, metadata, value) local player = Framework.GetPlayer(src) if not player then return end @@ -194,6 +223,9 @@ end -- Framework.GetMetadata(src, metadata) -- Gets the specified metadata key to the player's data. +---@param src number +---@param metadata string +---@return any|nil Framework.GetPlayerMetadata = function(src, metadata) local player = Framework.GetPlayer(src) if not player then return end @@ -203,6 +235,8 @@ end -- Framework.AddStress(src, value) -- Adds the specified value to the player's stress level and updates the client HUD. +---@param src number +---@param value number ---@return number | nil Framework.AddStress = function(src, value) local player = Framework.GetPlayer(src) @@ -216,6 +250,8 @@ end -- Framework.RemoveStress(src, value) -- Removes the specified value from the player's stress level and updates the client HUD. +---@param src number +---@param value number ---@return number | nil Framework.RemoveStress = function(src, value) local player = Framework.GetPlayer(src) @@ -229,6 +265,8 @@ end -- Framework.AddHunger(src, value) -- Adds the specified value from the player's hunger level. +---@param src number +---@param value number ---@return number | nil Framework.AddHunger = function(src, value) local player = Framework.GetPlayer(src) @@ -238,12 +276,13 @@ Framework.AddHunger = function(src, value) player.Functions.SetMetaData('hunger', Math.Clamp(newHunger, 0, 100)) TriggerClientEvent('hud:client:UpdateNeeds', src, newHunger, playerData.metadata.thirst) --TriggerClientEvent('hud:client:UpdateStress', src, newStress) - return newHunger end -- Framework.AddThirst(src, value) -- Adds the specified value from the player's thirst level. +---@param src number +---@param value number ---@return number | nil Framework.AddThirst = function(src, value) local player = Framework.GetPlayer(src) @@ -257,7 +296,7 @@ Framework.AddThirst = function(src, value) end ---This will get the hunger of a player ----@param src any +---@param src number ---@return number | nil Framework.GetHunger = function(src) local player = Framework.GetPlayer(src) @@ -267,6 +306,9 @@ Framework.GetHunger = function(src) return newHunger end +---This will return a boolean if the player is dead or in last stand. +---@param src number +---@return boolean|nil Framework.GetIsPlayerDead = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -274,6 +316,9 @@ Framework.GetIsPlayerDead = function(src) return playerData.metadata.isdead or playerData.metadata.inlaststand or false end +---This will revive a player, if the player is dead or in last stand. +---@param src number +---@return boolean Framework.RevivePlayer = function(src) src = tonumber(src) if not src then return false end @@ -295,6 +340,8 @@ end -- Framework.GetPlayerPhone(src) -- Returns the phone number of the player. +---@param src number +---@return string | nil Framework.GetPlayerPhone = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -304,6 +351,8 @@ end -- Framework.GetPlayerGang(src) -- Returns the gang name of the player. +---@param src number +---@return string | nil Framework.GetPlayerGang = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -340,6 +389,7 @@ Framework.GetPlayerJob = function(src) end ---This will return the players job name, job label, job grade label job grade level, boss status, and duty status in a table +---@param src number ---@return table | nil Framework.GetPlayerJobData = function(src) local player = Framework.GetPlayer(src) @@ -371,12 +421,13 @@ end ---This will toggle a players duty status ---@param src number ---@param status boolean ----@return nil +---@return boolean Framework.SetPlayerDuty = function(src, status) local player = Framework.GetPlayer(src) - if not player then return end + if not player then return false end player.Functions.SetJobDuty(status) TriggerEvent('QBCore:Server:SetDuty', src, player.PlayerData.job.onduty) + return true end -- Sets the player's job to the specified name and grade. @@ -428,27 +479,42 @@ end -- Framework.AddItem(src, item, amount, slot, metadata) -- Adds the specified item to the player's inventory. +---@param src number +---@param item string +---@param amount number +---@param slot number +---@param metadata table +---@return boolean | nil Framework.AddItem = function(src, item, amount, slot, metadata) local player = Framework.GetPlayer(src) if not player then return end - TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, - { action = "add", item = item, count = amount, slot = slot, metadata = metadata }) + TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, { action = "add", item = item, count = amount, slot = slot, metadata = metadata }) return player.Functions.AddItem(item, amount, slot, metadata) end -- Framework.RemoveItem(src, item, amount, slot, metadata) -- Removes the specified item from the player's inventory. +---@param src number +---@param item string +---@param amount number +---@param slot number +---@param metadata table +---@return boolean | nil Framework.RemoveItem = function(src, item, amount, slot, metadata) local player = Framework.GetPlayer(src) if not player then return end - TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, - { action = "remove", item = item, count = amount, slot = slot, metadata = metadata }) + TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, { action = "remove", item = item, count = amount, slot = slot, metadata = metadata }) return player.Functions.RemoveItem(item, amount, slot or nil) end -- Framework.SetMetadata(src, item, slot, metadata) -- Sets the metadata for the specified item in the player's inventory. -- Notes, this is kinda a jank workaround. with the framework aside from updating the entire table theres not really a better way +---@param src number +---@param item string +---@param slot number +---@param metadata table +---@return boolean | nil Framework.SetMetadata = function(src, item, slot, metadata) local player = Framework.GetPlayer(src) if not player then return end @@ -472,8 +538,7 @@ end ---@return table Framework.GetOwnedVehicles = function(src) local citizenId = Framework.GetPlayerIdentifier(src) - local result = MySQL.Sync.fetchAll("SELECT vehicle, plate FROM player_vehicles WHERE citizenid = '" .. - citizenId .. "'") + local result = MySQL.Sync.fetchAll("SELECT vehicle, plate FROM player_vehicles WHERE citizenid = '" .. citizenId .. "'") local vehicles = {} for i = 1, #result do local vehicle = result[i].vehicle @@ -485,6 +550,8 @@ end -- Framework.RegisterUsableItem(item, cb) -- Registers a usable item with a callback function. +---@param itemName string +---@param cb function Framework.RegisterUsableItem = function(itemName, cb) local func = function(src, item, itemData) itemData = itemData or item @@ -495,13 +562,13 @@ Framework.RegisterUsableItem = function(itemName, cb) QBCore.Functions.CreateUseableItem(itemName, func) end -RegisterNetEvent("QBCore:Server:OnPlayerLoaded", function() - local src = source +RegisterNetEvent("QBCore:Server:OnPlayerLoaded", function(src) + src = src or source TriggerEvent("community_bridge:Server:OnPlayerLoaded", src) end) -RegisterNetEvent("QBCore:Server:OnPlayerUnload", function(source) - local src = source +RegisterNetEvent("QBCore:Server:OnPlayerUnload", function(src) + src = src or source TriggerEvent("community_bridge:Server:OnPlayerUnload", src) end) diff --git a/modules/framework/qbx_core/client.lua b/modules/framework/qbx_core/client.lua index 8add8d7..f1cadd2 100644 --- a/modules/framework/qbx_core/client.lua +++ b/modules/framework/qbx_core/client.lua @@ -5,18 +5,27 @@ QBox = exports.qbx_core Framework = Framework or {} +---This will get the name of the framework being used (if a supported framework). +---@return string Framework.GetFrameworkName = function() return 'qbx_core' end +---This will return a table of the player data, this will be in the framework format. +---This is mainly for internal bridge use and should be avoided. +---@return table Framework.GetPlayerData = function() return QBox.GetPlayerData() end +---This will return a table of all the jobs in the framework. +---@return table Framework.GetFrameworkJobs = function() return QBox.GetJobs() end +---This will get the players birth date +---@return string Framework.GetPlayerDob = function() local playerData = Framework.GetPlayerData() return playerData.charinfo.birthdate @@ -24,11 +33,10 @@ end ---Will Display the help text message on the screen ---@param message string ----@param _ unknown +---@param position string ---@return nil -Framework.ShowHelpText = function(message, _) - if _ == nil then _ = 'left-center' end - return exports.ox_lib:showTextUI(message, { position = _position }) +Framework.ShowHelpText = function(message, position) + return exports.ox_lib:showTextUI(message, { position = position or 'top-center' }) end ---This will hide the help text message on the screen @@ -37,19 +45,32 @@ Framework.HideHelpText = function() return exports.ox_lib:hideTextUI() end +---This will return the players metadata for the specified metadata key. +---@param metadata table | string +---@return table | string | number | boolean Framework.GetPlayerMetaData = function(metadata) local playerData = Framework.GetPlayerData() return playerData.metadata[metadata] end +---This will send a notification to the player. +---@param message string +---@param type string +---@param time number +---@return nil Framework.Notify = function(message, type, time) return QBox:Notify("Notification", type, time, message) end +---This will get the players identifier (citizenid) etc. +---@return string Framework.GetPlayerIdentifier = function() return Framework.GetPlayerData().citizenid end +---This will get the players name (first and last). +---@return string +---@return string Framework.GetPlayerName = function() local playerData = Framework.GetPlayerData() return playerData.charinfo.firstname, playerData.charinfo.lastname @@ -81,11 +102,44 @@ Framework.GetPlayerJobData = function() } end +---This will return the players inventory as a table in the ox_inventory style flormat. +---@return table Framework.GetPlayerInventory = function() return Framework.GetPlayerData().items end ----comment +---This will return the vehicle properties for the specified vehicle. +---@param vehicle number +---@return table +Framework.GetVehicleProperties = function(vehicle) + if not vehicle or not DoesEntityExist(vehicle) then return {} end + local vehicleProps = lib.getVehicleProperties(vehicle) + return vehicleProps or {} +end + +---This will set the vehicle properties for the specified vehicle. +---@param vehicle number +---@param properties table +---@return boolean +Framework.SetVehicleProperties = function(vehicle, properties) + if not vehicle or not DoesEntityExist(vehicle) then return false end + if not properties then return false end + if NetworkGetEntityIsNetworked(vehicle) then + local vehNetID = NetworkGetNetworkIdFromEntity(vehicle) + local entOwner = GetPlayerServerId(NetworkGetEntityOwner(vehNetID)) + if entOwner ~= GetPlayerServerId(PlayerId()) then + NetworkRequestControlOfEntity(vehicle) + local count = 0 + while not NetworkHasControlOfEntity(vehicle) and count < 3000 do + Wait(1) + count = count + 1 + end + end + end + return true, lib.setVehicleProperties(vehicle, properties) +end + +---This will return the item count for the specified item in the players inventory. ---@param item string ---@return number Framework.GetItemCount = function(item) @@ -93,6 +147,8 @@ Framework.GetItemCount = function(item) return 0, print("Community_bridge:WARN: GetItemCount is not implemented for this framework, please use the inventory module to get the item count. If you are using a diffrent inventory please let us know so we can bridge it and have less nonsense.") end +---This will get a players dead status. +---@return boolean Framework.GetIsPlayerDead = function() local platerData = Framework.GetPlayerData() return platerData.metadata["isdead"] or platerData.metadata["inlaststand"] diff --git a/modules/framework/qbx_core/server.lua b/modules/framework/qbx_core/server.lua index a7064b7..af425b8 100644 --- a/modules/framework/qbx_core/server.lua +++ b/modules/framework/qbx_core/server.lua @@ -1,19 +1,27 @@ ---@diagnostic disable: duplicate-set-field if GetResourceState('qbx_core') ~= 'started' then return end -local QBox = exports.qbx_core - Framework = Framework or {} +local QBox = exports.qbx_core + ---Returns the name of the framework being used (if a supported framework). ---@return string Framework.GetFrameworkName = function() return 'qbx_core' end +---This will return if the player is an admin in the framework. +---@param src any +---@return boolean +Framework.GetIsFrameworkAdmin = function(src) + if not src then return false end + return IsPlayerAceAllowed(src, 'admin') +end + ---Returns the player date of birth. ---@param src number ----@return string +---@return string|nil Framework.GetPlayerDob = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -69,11 +77,12 @@ Framework.GetPlayerName = function(src) return playerData.charinfo.firstname, playerData.charinfo.lastname end --- Returns a table of items matching the specified name and if passed metadata from the player's inventory. +---Returns a table of items matching the specified name and if passed metadata from the player's inventory. +---returns {name = v.name, count = v.amount, metadata = v.info, slot = v.slot} ---@param src number ---@param item string ---@param metadata table ----@return table +---@return table|nil Framework.GetItem = function(src, item, metadata) local player = Framework.GetPlayer(src) if not player then return end @@ -203,7 +212,7 @@ Framework.AddHunger = function(src, value) return newHunger end --- Adds the specified value from the player's thirst level. +---Adds the specified value from the player's thirst level. ---@param src number ---@param value number ---@return number | nil @@ -228,6 +237,9 @@ Framework.GetHunger = function(src) return newHunger end +---This will return a boolean if the player is dead or in last stand. +---@param src number +---@return boolean|nil Framework.GetIsPlayerDead = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -235,6 +247,9 @@ Framework.GetIsPlayerDead = function(src) return playerData.metadata.isdead or false end +---This will revive a player, if the player is dead or in last stand. +---@param src number +---@return boolean Framework.RevivePlayer = function(src) src = tonumber(src) if not src then return false end @@ -244,7 +259,7 @@ end ---This will return the players thirst level. ---@param src number ----@return number +---@return number| nil Framework.GetThirst = function(src) local player = Framework.GetPlayer(src) if not player then return end @@ -299,6 +314,7 @@ Framework.GetPlayerJob = function(src) end ---This will return the players job name, job label, job grade label job grade level, boss status, and duty status in a table +---@param src number ---@return table | nil Framework.GetPlayerJobData = function(src) local player = Framework.GetPlayer(src) @@ -395,8 +411,7 @@ end Framework.AddItem = function(src, item, amount, slot, metadata) local player = Framework.GetPlayer(src) if not player then return end - TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, - { action = "add", item = item, count = amount, slot = slot, metadata = metadata }) + TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, { action = "add", item = item, count = amount, slot = slot, metadata = metadata }) return player.Functions.AddItem(item, amount, slot, metadata) end @@ -410,13 +425,12 @@ end Framework.RemoveItem = function(src, item, amount, slot, metadata) local player = Framework.GetPlayer(src) if not player then return end - TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, - { action = "remove", item = item, count = amount, slot = slot, metadata = metadata }) + TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, { action = "remove", item = item, count = amount, slot = slot, metadata = metadata }) return player.Functions.RemoveItem(item, amount, slot) end ---Sets the metadata for the specified item in the player's inventory. ------@param src number +---@param src number ---@param item string ---@param slot number ---@param metadata table @@ -433,8 +447,7 @@ end ---@return table Framework.GetOwnedVehicles = function(src) local citizenId = Framework.GetPlayerIdentifier(src) - local result = MySQL.Sync.fetchAll("SELECT vehicle, plate FROM player_vehicles WHERE citizenid = '" .. - citizenId .. "'") + local result = MySQL.Sync.fetchAll("SELECT vehicle, plate FROM player_vehicles WHERE citizenid = '" .. citizenId .. "'") local vehicles = {} for i = 1, #result do local vehicle = result[i].vehicle @@ -458,13 +471,13 @@ Framework.RegisterUsableItem = function(itemName, cb) return QBox:CreateUseableItem(itemName, func) end -RegisterNetEvent("QBCore:Server:OnPlayerLoaded", function() - local src = source +RegisterNetEvent("QBCore:Server:OnPlayerLoaded", function(src) + src = src or source TriggerEvent("community_bridge:Server:OnPlayerLoaded", src) end) -RegisterNetEvent("QBCore:Server:OnPlayerUnload", function() - local src = source +RegisterNetEvent("QBCore:Server:OnPlayerUnload", function(src) + src = src or source TriggerEvent("community_bridge:Server:OnPlayerUnload", src) end) diff --git a/modules/fuel/_default/client.lua b/modules/fuel/_default/client.lua index 731ace5..0e4e9c1 100644 --- a/modules/fuel/_default/client.lua +++ b/modules/fuel/_default/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field Fuel = Fuel or {} diff --git a/modules/fuel/bigDaddy-Fuel/client.lua b/modules/fuel/bigDaddy-Fuel/client.lua index 00f8f75..941f529 100644 --- a/modules/fuel/bigDaddy-Fuel/client.lua +++ b/modules/fuel/bigDaddy-Fuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "BigDaddy-Fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/cdn-fuel/client.lua b/modules/fuel/cdn-fuel/client.lua index 1dba7dd..c94ead0 100644 --- a/modules/fuel/cdn-fuel/client.lua +++ b/modules/fuel/cdn-fuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "cdn-fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/esx-sna-fuel/client.lua b/modules/fuel/esx-sna-fuel/client.lua index cc15388..8205284 100644 --- a/modules/fuel/esx-sna-fuel/client.lua +++ b/modules/fuel/esx-sna-fuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "esx-sna-fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/lc_fuel/client.lua b/modules/fuel/lc_fuel/client.lua index 551aef2..21b03a3 100644 --- a/modules/fuel/lc_fuel/client.lua +++ b/modules/fuel/lc_fuel/client.lua @@ -1,8 +1,6 @@ ---@diagnostic disable: duplicate-set-field local resourceName = "lc_fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/legacyfuel/client.lua b/modules/fuel/legacyfuel/client.lua index 4903687..fc95740 100644 --- a/modules/fuel/legacyfuel/client.lua +++ b/modules/fuel/legacyfuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "LegacyFuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/okokGasStation/client.lua b/modules/fuel/okokGasStation/client.lua index 42785fe..0069a12 100644 --- a/modules/fuel/okokGasStation/client.lua +++ b/modules/fuel/okokGasStation/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "okokGasStation" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/ox_fuel/client.lua b/modules/fuel/ox_fuel/client.lua index 1001582..7008bab 100644 --- a/modules/fuel/ox_fuel/client.lua +++ b/modules/fuel/ox_fuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "ox_fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). @@ -25,7 +24,7 @@ end Fuel.SetFuel = function(vehicle, fuel, type) if not DoesEntityExist(vehicle) then return end local currentFuel = Entity(vehicle).state.fuel - Entity(vehicle).state.fuel = currentFuel + fuel + Entity(vehicle).state.fuel = currentFuel and currentFuel + fuel or fuel return Entity(vehicle).state.fuel end diff --git a/modules/fuel/ps-fuel/client.lua b/modules/fuel/ps-fuel/client.lua index ee84b1a..f083538 100644 --- a/modules/fuel/ps-fuel/client.lua +++ b/modules/fuel/ps-fuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "ps-fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/qs-fuelstations/client.lua b/modules/fuel/qs-fuelstations/client.lua index ab5c571..ec4a91e 100644 --- a/modules/fuel/qs-fuelstations/client.lua +++ b/modules/fuel/qs-fuelstations/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "qs-fuelstations" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/renewed-Fuel/client.lua b/modules/fuel/renewed-Fuel/client.lua index 8ed1f66..0408a99 100644 --- a/modules/fuel/renewed-Fuel/client.lua +++ b/modules/fuel/renewed-Fuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "Renewed-Fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/ti_fuel/client.lua b/modules/fuel/ti_fuel/client.lua index 54471e2..7c9e77d 100644 --- a/modules/fuel/ti_fuel/client.lua +++ b/modules/fuel/ti_fuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "ti_fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/fuel/x-fuel/client.lua b/modules/fuel/x-fuel/client.lua index b00f604..fc2d054 100644 --- a/modules/fuel/x-fuel/client.lua +++ b/modules/fuel/x-fuel/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "x-fuel" -local configValue = BridgeClientConfig.Fuel -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Fuel = Fuel or {} ---This will get the name of the Fuel being used (if a supported Fuel). diff --git a/modules/helptext/_default/client.lua b/modules/helptext/_default/client.lua index bfab021..8494c66 100644 --- a/modules/helptext/_default/client.lua +++ b/modules/helptext/_default/client.lua @@ -1,17 +1,16 @@ +---@diagnostic disable: duplicate-set-field HelpText = HelpText or {} ---This will show a help text message at the screen position passed ---@param message string ---@param _position string ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.ShowHelpText = function(message, _position) return Framework.ShowHelpText(message, _position) end ---This will hide the help text message on the screen ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.HideHelpText = function() return Framework.HideHelpText() end diff --git a/modules/helptext/_default/server.lua b/modules/helptext/_default/server.lua index c670c93..fe80525 100644 --- a/modules/helptext/_default/server.lua +++ b/modules/helptext/_default/server.lua @@ -1,17 +1,16 @@ +---@diagnostic disable: duplicate-set-field HelpText = HelpText or {} ---This will show a help text message to the specified player at the screen position passed ---@param src number ---@param message string ---@param position string ----@diagnostic disable-next-line: duplicate-set-field HelpText.ShowHelpText = function(src, message, position) TriggerClientEvent('community_bridge:Client:ShowHelpText', src, message, position) end ---This will hide the help text message on the screen for the specified player ---@param src number ----@diagnostic disable-next-line: duplicate-set-field HelpText.HideHelpText = function(src) TriggerClientEvent('community_bridge:Client:HideHelpText', src) end diff --git a/modules/helptext/cd_drawtextui/client.lua b/modules/helptext/cd_drawtextui/client.lua index 9d55f2e..d257822 100644 --- a/modules/helptext/cd_drawtextui/client.lua +++ b/modules/helptext/cd_drawtextui/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field HelpText = HelpText or {} local resourceName = "cd_drawtextui" local configValue = BridgeSharedConfig.HelpText @@ -8,14 +9,12 @@ if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (c ---@param message string ---@param _position string ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.ShowHelpText = function(message, _position) return TriggerEvent('cd_drawtextui:ShowUI', 'show', message) end ---This will hide the help text message on the screen ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.HideHelpText = function() return TriggerEvent('cd_drawtextui:HideUI') end diff --git a/modules/helptext/jg-textui/client.lua b/modules/helptext/jg-textui/client.lua index cc6d4f8..bceec6d 100644 --- a/modules/helptext/jg-textui/client.lua +++ b/modules/helptext/jg-textui/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field HelpText = HelpText or {} local resourceName = "jg-textui" local configValue = BridgeSharedConfig.HelpText @@ -7,14 +8,12 @@ if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (c ---@param message string ---@param _position string ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.ShowHelpText = function(message, _position) return exports['jg-textui']:DrawText(message) end ---This will hide the help text message on the screen ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.HideHelpText = function() return exports['jg-textui']:HideText() end diff --git a/modules/helptext/lab-HintUI/client.lua b/modules/helptext/lab-HintUI/client.lua index 0ddccb9..f72fdd9 100644 --- a/modules/helptext/lab-HintUI/client.lua +++ b/modules/helptext/lab-HintUI/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field HelpText = HelpText or {} local resourceName = "lab-HintUI" local configValue = BridgeSharedConfig.HelpText @@ -7,14 +8,12 @@ if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (c ---@param message string ---@param _position string ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.ShowHelpText = function(message, _position) return exports['lab-HintUI']:Show(message, "Hint Text") end ---This will hide the help text message on the screen ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.HideHelpText = function() return exports['lab-HintUI']:Hide() end diff --git a/modules/helptext/okokTextUI/client.lua b/modules/helptext/okokTextUI/client.lua index fec30be..7ad8a0e 100644 --- a/modules/helptext/okokTextUI/client.lua +++ b/modules/helptext/okokTextUI/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field HelpText = HelpText or {} local resourceName = "okokTextUI" local configValue = BridgeSharedConfig.HelpText @@ -7,14 +8,12 @@ if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (c ---@param message string ---@param _position string ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.ShowHelpText = function(message, _position) return exports['okokTextUI']:Open(message, 'darkblue', _position, false) end ---This will hide the help text message on the screen ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.HideHelpText = function() return exports['okokTextUI']:Close() end diff --git a/modules/helptext/ox_lib/client.lua b/modules/helptext/ox_lib/client.lua index 4fe01d3..e36abff 100644 --- a/modules/helptext/ox_lib/client.lua +++ b/modules/helptext/ox_lib/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field HelpText = HelpText or {} local resourceName = "ox_lib" local configValue = BridgeSharedConfig.HelpText @@ -5,17 +6,16 @@ if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (c ---This will show a help text message at the screen position passed ---@param message string ----@param _position string +---@param position string ---@return nil ----@diagnostic disable-next-line: duplicate-set-field -HelpText.ShowHelpText = function(message, _position) - if _position == nil then _position = 'left-center' end - return exports.ox_lib:showTextUI(message, { position = _position }) +HelpText.ShowHelpText = function(message, position) + return exports.ox_lib:showTextUI(message, { + position = position or 'top-center' + }) end ---This will hide the help text message on the screen ---@return nil ----@diagnostic disable-next-line: duplicate-set-field HelpText.HideHelpText = function() return exports.ox_lib:hideTextUI() end diff --git a/modules/housing/bcs-housing/client.lua b/modules/housing/bcs-housing/client.lua index 398b713..ab420d2 100644 --- a/modules/housing/bcs-housing/client.lua +++ b/modules/housing/bcs-housing/client.lua @@ -1,4 +1,4 @@ -if GetResourceState('bcs-housing') ~= 'started' then return end +if GetResourceState('bcs-housing') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/bcs-housing/server.lua b/modules/housing/bcs-housing/server.lua index 7a8f747..3745ce9 100644 --- a/modules/housing/bcs-housing/server.lua +++ b/modules/housing/bcs-housing/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('bcs-housing') ~= 'started' then return end +if GetResourceState('bcs-housing') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/esx_property/client.lua b/modules/housing/esx_property/client.lua index dc61c00..50ca417 100644 --- a/modules/housing/esx_property/client.lua +++ b/modules/housing/esx_property/client.lua @@ -1,4 +1,4 @@ -if GetResourceState('esx_property') ~= 'started' then return end +if GetResourceState('esx_property') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/esx_property/server.lua b/modules/housing/esx_property/server.lua index 118fa7a..420a2f0 100644 --- a/modules/housing/esx_property/server.lua +++ b/modules/housing/esx_property/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('esx_property') ~= 'started' then return end +if GetResourceState('esx_property') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/ps-housing/client.lua b/modules/housing/ps-housing/client.lua index b7f5d8e..a174c0f 100644 --- a/modules/housing/ps-housing/client.lua +++ b/modules/housing/ps-housing/client.lua @@ -1,4 +1,4 @@ -if GetResourceState('ps-housing') ~= 'started' then return end +if GetResourceState('ps-housing') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/ps-housing/server.lua b/modules/housing/ps-housing/server.lua index 52a2e48..e4640d2 100644 --- a/modules/housing/ps-housing/server.lua +++ b/modules/housing/ps-housing/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('ps-housing') ~= 'started' then return end +if GetResourceState('ps-housing') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/qb-appartments/client.lua b/modules/housing/qb-appartments/client.lua index 2ce29c9..415e0da 100644 --- a/modules/housing/qb-appartments/client.lua +++ b/modules/housing/qb-appartments/client.lua @@ -1,4 +1,4 @@ -if GetResourceState('qb-appartments') ~= 'started' then return end +if GetResourceState('qb-appartments') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/qb-appartments/server.lua b/modules/housing/qb-appartments/server.lua index cfd0982..9b92c1f 100644 --- a/modules/housing/qb-appartments/server.lua +++ b/modules/housing/qb-appartments/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('qb-appartments') ~= 'started' then return end +if GetResourceState('qb-appartments') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/qb-houses/client.lua b/modules/housing/qb-houses/client.lua index 4208627..1733b77 100644 --- a/modules/housing/qb-houses/client.lua +++ b/modules/housing/qb-houses/client.lua @@ -1,4 +1,4 @@ -if GetResourceState('qb-houses') ~= 'started' then return end +if GetResourceState('qb-houses') == 'missing' then return end Housing = Housing or {} diff --git a/modules/housing/qb-houses/server.lua b/modules/housing/qb-houses/server.lua index a06d537..f2d4265 100644 --- a/modules/housing/qb-houses/server.lua +++ b/modules/housing/qb-houses/server.lua @@ -1,4 +1,4 @@ -if GetResourceState('qb-houses') ~= 'started' then return end +if GetResourceState('qb-houses') == 'missing' then return end Housing = Housing or {} diff --git a/modules/input/_qb-input.lua b/modules/input/_default/client.lua similarity index 65% rename from modules/input/_qb-input.lua rename to modules/input/_default/client.lua index 375c052..d3e6a8f 100644 --- a/modules/input/_qb-input.lua +++ b/modules/input/_default/client.lua @@ -1,6 +1,44 @@ -local resourceName = "qb-input" -local configValue = BridgeClientConfig.InputSystem -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +function QBTypeToOxType(_type) + if _type == "text" then + return "input" + elseif _type == "password" then + return "input" + elseif _type == "number" then + return "number" + elseif _type == "radio" then + return "checkbox" + elseif _type == "checkbox" then + return "checkbox" + elseif _type == "select" then + return "select" + end +end + +function QBToOxInput(data) + local returnData = {} + for i, v in pairs(data) do + local input = { + label = v.text, + name = i, + type = QBTypeToOxType(v.type), + required = v.isRequired, + default = v.placeholder, + } + if v.type == "select" then + input.options = {} + for i, v in pairs(v.options) do + table.insert(input.options, {value = v.value, label = v.text}) + end + elseif v.type == "checkbox" then + for i, v in pairs(v.options) do + table.insert(returnData, {value = v.value, label = v.text}) + end + end + table.insert(returnData, input) + end + return returnData +end + function OxTypeToQBType(_type) if _type == "input" then @@ -58,35 +96,4 @@ function OxToQBInput(data) table.insert(returnData, input) end return returnData -end - -function OpenInput(title, data, isQBFormat, submitText) - local input = data.inputs - if not isQBFormat then - input = OxToQBInput(data) - end - local returnData = exports['qb-input']:ShowInput({ - header = title, - submitText = submitText or "Submit", - inputs = input - }) - if not returnData then return end - if returnData[1] then return returnData end - --converting to standard format (ox) - local convertedData = {} - if isQBFormat then - for i, v in pairs(input) do - for k, j in pairs(returnData) do - if k == v.text then - convertedData[tonumber(i)] = j - end - end - end - return convertedData - end - - for i, v in pairs(returnData) do - convertedData[tonumber(i)] = v - end - return convertedData -end +end \ No newline at end of file diff --git a/modules/input/client.lua b/modules/input/_default/olddata.lua similarity index 90% rename from modules/input/client.lua rename to modules/input/_default/olddata.lua index 1650cce..e61152b 100644 --- a/modules/input/client.lua +++ b/modules/input/_default/olddata.lua @@ -1,6 +1,6 @@ -if GetResourceState('ox_lib') ~= 'started' and GetResourceState('qb-menu') ~= 'started' then return end --- { +-- if GetResourceState('ox_lib') ~= 'started' and GetResourceState('qb-menu') ~= 'started' then return end +-- -- { -- header = "Test", -- submitText = "Bill", -- inputs = { @@ -76,38 +76,38 @@ if GetResourceState('ox_lib') ~= 'started' and GetResourceState('qb-menu') ~= 's --QB types: text, password, number, radio, checkbox, select, -- -- "input", "number", "checkbox", "select", "multi-select", "slider", "color", "date", "date-range", "time", "textarea", -Input = {} +-- Input = {} --- qb to ox ---Open menu +-- -- qb to ox +-- --Open menu -function Input.Open(title, data, isQBFormat, submitText) - if isQBFormat then - local inputs = data.inputs - if BridgeClientConfig.InputSystem == "ox" then - return lib.inputDialog(title, QBToOxInput(inputs)) - elseif BridgeClientConfig.InputSystem == "qb" then - return exports['qb-input']:ShowInput({ - header = title, - submitText = submitText or "Submit", - inputs = inputs - }) - end - else - if BridgeClientConfig.InputSystem == "ox" then - return lib.inputDialog(title, data) - elseif BridgeClientConfig.InputSystem == "qb" then - return exports['qb-input']:ShowInput({ - header = title, - submitText = submitText or "Submit", - inputs = OxToQBInput(data) - }) - end - end - return OpenInput(title, data, isQBFormat, submitText) -end +-- function Input.Open(title, data, isQBFormat, submitText) +-- if isQBFormat then +-- local inputs = data.inputs +-- if BridgeClientConfig.InputSystem == "ox" then +-- return lib.inputDialog(title, QBToOxInput(inputs)) +-- elseif BridgeClientConfig.InputSystem == "qb" then +-- return exports['qb-input']:ShowInput({ +-- header = title, +-- submitText = submitText or "Submit", +-- inputs = inputs +-- }) +-- end +-- else +-- if BridgeClientConfig.InputSystem == "ox" then +-- return lib.inputDialog(title, data) +-- elseif BridgeClientConfig.InputSystem == "qb" then +-- return exports['qb-input']:ShowInput({ +-- header = title, +-- submitText = submitText or "Submit", +-- inputs = OxToQBInput(data) +-- }) +-- end +-- end +-- return OpenInput(title, data, isQBFormat, submitText) +-- end -return Input +-- return Input --[[ diff --git a/modules/input/_oxlib.lua b/modules/input/_oxlib.lua deleted file mode 100644 index 6baa54c..0000000 --- a/modules/input/_oxlib.lua +++ /dev/null @@ -1,53 +0,0 @@ -local resourceName = "ox_lib" -local configValue = BridgeClientConfig.InputSystem -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - -function QBTypeToOxType(_type) - if _type == "text" then - return "input" - elseif _type == "password" then - return "input" - elseif _type == "number" then - return "number" - elseif _type == "radio" then - return "checkbox" - elseif _type == "checkbox" then - return "checkbox" - elseif _type == "select" then - return "select" - end -end - -function QBToOxInput(data) - local returnData = {} - for i, v in pairs(data) do - local input = { - label = v.text, - name = i, - type = QBTypeToOxType(v.type), - required = v.isRequired, - default = v.placeholder, - } - if v.type == "select" then - input.options = {} - for i, v in pairs(v.options) do - table.insert(input.options, {value = v.value, label = v.text}) - end - elseif v.type == "checkbox" then - for i, v in pairs(v.options) do - table.insert(returnData, {value = v.value, label = v.text}) - end - end - table.insert(returnData, input) - end - return returnData -end - -function OpenInput(title, data, isQBFormat, submitText) - local inputs = data.inputs - if isQBFormat then - return lib.inputDialog(title, QBToOxInput(inputs)) - else - return lib.inputDialog(title, data) - end -end \ No newline at end of file diff --git a/modules/input/_qb-input/client.lua b/modules/input/_qb-input/client.lua new file mode 100644 index 0000000..946c018 --- /dev/null +++ b/modules/input/_qb-input/client.lua @@ -0,0 +1,48 @@ +---@diagnostic disable: duplicate-set-field +local resourceName = "qb-input" +local configValue = BridgeClientConfig.InputSystem +if (configValue == "auto" and GetResourceState(resourceName) == "missing") or (configValue ~= "auto" and configValue ~= resourceName) then return end + +Input = {} + + +-- this probably needs improvement +function Input.Open(title, data, isQBFormat, submitText) + local input = data.inputs + if not isQBFormat then + input = OxToQBInput(data) + end + local returnData = exports['qb-input']:ShowInput({ + header = title, + submitText = submitText or "Submit", + inputs = input + }) + if not returnData then return end + print(json.encode(returnData)) + if returnData[1] then return returnData end + --converting to standard format (ox) + local convertedData = {} + if isQBFormat then + for i, v in pairs(input) do + print("Converting input: " .. v.name) + for k, j in pairs(returnData) do + if k == v.name then + convertedData[tonumber(i)] = j + end + end + end + return convertedData + end + + for i, v in pairs(returnData) do + local index = i and tonumber(i) + if not index then + table.insert(convertedData, v) + else + convertedData[index] = v + end + end + return convertedData +end + +return Input diff --git a/modules/input/ox_lib/client.lua b/modules/input/ox_lib/client.lua new file mode 100644 index 0000000..fa379ff --- /dev/null +++ b/modules/input/ox_lib/client.lua @@ -0,0 +1,17 @@ +---@diagnostic disable: duplicate-set-field +local resourceName = "ox_lib" +local configValue = BridgeClientConfig.InputSystem +if (configValue == "auto" and GetResourceState(resourceName) == "missing") or (configValue ~= "auto" and configValue ~= resourceName) then return end + +Input = {} +function Input.Open(title, data, isQBFormat, submitText) + local inputs = data.inputs + if isQBFormat then + return lib.inputDialog(title, QBToOxInput(inputs)) + else + return lib.inputDialog(title, data) + end +end + +return Input + diff --git a/modules/inventory/_default/server.lua b/modules/inventory/_default/server.lua index ebde24c..df4fa94 100644 --- a/modules/inventory/_default/server.lua +++ b/modules/inventory/_default/server.lua @@ -26,7 +26,25 @@ Inventory.RemoveItem = function(src, item, count, slot, metadata) return Framework.RemoveItem(src, item, count, slot, metadata) end ----This will return a table with the item info, {name, label, stack, weight, description, image} +---This will add items to a trunk, and return true or false based on success +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + return false, Prints.Error("This Inventory Has Not Been Bridged For A Trunk Feature.") +end + +---This will clear the specified inventory, will return success or failure. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return false, Prints.Error("This Inventory Has Not Been Bridged For A ClearStash Feature.") +end + +---This will return a table with the item info, +---example: {name = "coolitem", label = "a cool item name", stack = false, weight = 1000, description = "some item description", image = "coolitem.png"} ---@param item string ---@return table Inventory.GetItemInfo = function(item) @@ -34,8 +52,8 @@ Inventory.GetItemInfo = function(item) end ---This will return the count of the item in the players inventory, if not found will return 0. ---- ---if metadata is passed it will find the matching items count. +---example: 0 ---@param src number ---@param item string ---@param metadata table @@ -45,6 +63,7 @@ Inventory.GetItemCount = function(src, item, metadata) end ---This wil return the players inventory. +---example: {{weight = 10, name = "farts", metadata = {description = "this is a description"}, slot = 1, label = "stinky", count = 1}, {weight = 10, name = "farts", metadata = {description = "this is a description"}, slot = 2, label = "stinky", count = 1}} ---@param src number ---@return table Inventory.GetPlayerInventory = function(src) @@ -52,8 +71,7 @@ Inventory.GetPlayerInventory = function(src) end ---Returns the specified slot data as a table. ---- ----format {weight, name, metadata, slot, label, count} +---example {weight = 10, name = "farts", metadata = {description = "this is a description"}, slot = 1, label = "stinky", count = 1} ---@param src number ---@param slot number ---@return table @@ -73,20 +91,17 @@ end ---This will open the specified stash for the src passed. ---@param src number ----@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table +---@param _type string +---@param id number|string ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] return false, Prints.Error("This Inventory Has Not Been Bridged For A Stash Feature.") end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -94,8 +109,19 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - return false, Prints.Error("This Inventory Has Not Been Bridged For A Stash Feature.") + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + return true, id end ---This will return a boolean if the player has the item. @@ -131,11 +157,11 @@ Inventory.OpenShop = function(src, shopTitle) end -- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups) +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) return false, Prints.Error("This Inventory Has Not Been Bridged For A CreateShop Feature.") end @@ -146,6 +172,10 @@ Inventory.GetImagePath = function(item) return "https://avatars.githubusercontent.com/u/47620135" end +---This will remove the file extension from the item name if present. +---example: "item.png" will become "item" +---@param item string +---@return string Inventory.StripPNG = function(item) if string.find(item, ".png") then item = string.gsub(item, ".png", "") diff --git a/modules/inventory/codem-inventory/server.lua b/modules/inventory/codem-inventory/server.lua index 0718c83..e87c299 100644 --- a/modules/inventory/codem-inventory/server.lua +++ b/modules/inventory/codem-inventory/server.lua @@ -2,6 +2,7 @@ if GetResourceState('codem-inventory') ~= 'started' then return end Inventory = Inventory or {} +Inventory.Stashes = Inventory.Stashes or {} local codem = exports['codem-inventory'] @@ -64,7 +65,6 @@ Inventory.GetPlayerInventory = function(src) end ---Returns the specified slot data as a table. ---- ---format {weight, name, metadata, slot, label, count} ---@param src number ---@param slot number @@ -96,20 +96,18 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - TriggerClientEvent('community_bridge:client:codem-inventory:openStash', src, id, { label = label, slots = slots, weight = weight }) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] + TriggerClientEvent('community_bridge:client:codem-inventory:openStash', src, id, { label = tbl.label, slots = tbl.slots, weight = tbl.weight }) end + ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -117,8 +115,19 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - return true + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + return true, id end ---This will return a boolean if the player has the item. @@ -138,6 +147,25 @@ Inventory.CanCarryItem = function(src, item, count) return true end +---This will add items to a trunk, and return true or false based on success +---If a trunk with the identifier does not exist, it will create one with default values. +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + if type(items) ~= "table" then return false end + return false, print("AddItemsToTrunk is not implemented in codem-inventory, because of this we dont have a way to add items to a trunk.") +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return false, print("ClearInventory is not implemented in codem-inventory, because of this we dont have a way to clear a stash.") +end + ---This will update the plate to the vehicle inside the inventory. (It will also update with jg-mechanic if using it) ---@param oldplate string ---@param newplate string @@ -165,11 +193,11 @@ Inventory.OpenShop = function(src, shopTitle) end -- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups) +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) return true, print("Unable to Create Shop for codem-inventory, I do not have access to a copy of this inventory to bridge the feature.") end diff --git a/modules/inventory/core_inventory/server.lua b/modules/inventory/core_inventory/server.lua index 43f1a25..baf9fb5 100644 --- a/modules/inventory/core_inventory/server.lua +++ b/modules/inventory/core_inventory/server.lua @@ -2,7 +2,7 @@ if GetResourceState('core_inventory') ~= 'started' then return end Inventory = Inventory or {} - +Inventory.Stashes = Inventory.Stashes or {} local core = exports.core_inventory ---This will add an item, and return true or false based on success @@ -52,7 +52,6 @@ Inventory.RemoveItem = function(src, item, count, slot, metadata) end ---This will return the count of the item in the players inventory, if not found will return 0. ---- ---if metadata is passed it will find the matching items count. ---@param src number ---@param item string @@ -78,21 +77,38 @@ end ---@param src number ---@return table Inventory.GetPlayerInventory = function(src) + local frameworkInUse = Bridge.Framework.GetFrameworkName() + if frameworkInUse == 'qb-core' then + return Bridge.Framework.GetPlayerInventory(src) + end local playerItems = core:getInventory(src) local repackedTable = {} for _, v in pairs(playerItems) do - table.insert(repackedTable, { - name = v.name, - count = v.count, - metadata = v.metadata, - slot = v.id, - }) + if v.metadata and v.count > 1 then + local plaseFixThisExportCuzThisIsPainful = core:getItems(src, v.name) + if plaseFixThisExportCuzThisIsPainful then + for _, item in pairs(plaseFixThisExportCuzThisIsPainful) do + table.insert(repackedTable, { + name = v.name, + count = item.count, + metadata = item.metadata, + slot = item.id, + }) + end + end + else + table.insert(repackedTable, { + name = v.name, + count = v.count, + metadata = v.metadata, + slot = v.id, + }) + end end return repackedTable end ---Returns the specified slot data as a table. ---- ---format {weight, name, metadata, slot, label, count} ---@param src number ---@param slot number @@ -125,22 +141,17 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - if not slots then slots = 30 end - local mathyShit = slots / 2 - core:openInventory(playerid, id, 'stash', mathyShit, mathyShit, true, nil, false) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] + core:openInventory(src, id, _type, tbl.slots, tbl.weight, true, nil, false) end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -148,11 +159,21 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) + if Inventory.Stashes[id] then return true, id end if not slots then slots = 30 end local mathyShit = slots / 2 - core:openInventory(nil, id, 'stash', mathyShit, mathyShit, false, nil, false) - return true + Inventory.Stashes[id] = { + id = id, + label = label, + slots = mathyShit, + weight = mathyShit, + owner = owner, + groups = groups, + coords = coords + } + return true, id end ---This will return a boolean if the player has the item. @@ -172,6 +193,25 @@ Inventory.CanCarryItem = function(src, item, count) return true end +---This will add items to a trunk, and return true or false based on success +---If a trunk with the identifier does not exist, it will create one with default values. +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + if type(items) ~= "table" then return false end + return false, print("AddItemsToTrunk is not implemented in core_inventory, because of this we dont have a way to add items to a trunk.") +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return false, print("ClearInventory is not implemented in core_inventory, because of this we dont have a way to clear a stash.") +end + ---This will update the plate to the vehicle inside the inventory. (It will also update with jg-mechanic if using it) ---@param oldplate string ---@param newplate string @@ -204,25 +244,24 @@ Inventory.GetImagePath = function(item) return imagePath or "https://avatars.githubusercontent.com/u/47620135" end --- This will open the specified shop for the src passed. +---This will open the specified shop for the src passed. ---@param src number ---@param shopTitle string Inventory.OpenShop = function(src, shopTitle) return false, print("Unable to open shop for core_inventory, I do not have access to a copy of this inventory to bridge the feature.") end --- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups) +---This will register a shop, if it already exists it will return true. +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) return false, print("Unable to open shop for core_inventory, I do not have access to a copy of this inventory to bridge the feature.") end - ---<-- TODO swap to internal callback system --- This is used for the esx users, documentation doesnt show a client side available option for the inventory so we use jank callbacks to get this. +---<-- TODO swap to internal callback system +---This is used for the esx users, documentation doesnt show a client side available option for the inventory so we use jank callbacks to get this. lib.callback.register('community_bridge:Callback:core_inventory', function(source) local items = core:getItemsList() return items or {} diff --git a/modules/inventory/jpr-inventory/server.lua b/modules/inventory/jpr-inventory/server.lua index 81f4dc0..53fdefb 100644 --- a/modules/inventory/jpr-inventory/server.lua +++ b/modules/inventory/jpr-inventory/server.lua @@ -5,6 +5,7 @@ local jpr = exports['jpr-inventory'] local registeredShops = {} Inventory = Inventory or {} +Inventory.Stashes = Inventory.Stashes or {} ---This will add an item, and return true or false based on success ---@param src number @@ -40,7 +41,6 @@ Inventory.GetItemInfo = function(item) end ---Returns the specified slot data as a table. ---- ---format {weight, name, metadata, slot, label, count} ---@param src number ---@param slot number @@ -62,20 +62,17 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - TriggerClientEvent('community_bridge:client:jpr-inventory:openStash', src, id, { weight = weight, slots = slots }) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] + TriggerClientEvent('community_bridge:client:jpr-inventory:openStash', src, id, { weight = tbl.weight, slots = tbl.slots }) end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -83,8 +80,38 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - return true + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + return true, id +end + +---This will add items to a trunk, and return true or false based on success +---If a trunk with the identifier does not exist, it will create one with default values. +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + if type(items) ~= "table" then return false end + return false, print("AddItemsToTrunk is not implemented in jpr-inventory, because of this we dont have a way to add items to a trunk.") +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return false, print("ClearInventory is not implemented in jpr-inventory, because of this we dont have a way to clear a stash.") end ---This will return a boolean if the player has the item. @@ -129,19 +156,19 @@ Inventory.GetImagePath = function(item) return imagePath or "https://avatars.githubusercontent.com/u/47620135" end --- This will open the specified shop for the src passed. +---This will open the specified shop for the src passed. ---@param src number ---@param shopTitle string Inventory.OpenShop = function(src, shopTitle) jpr:OpenShop(src, shopTitle) end --- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups) +---This will register a shop, if it already exists it will return true. +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) if not shopTitle or not shopInventory or not shopCoords then return end if registeredShops[shopTitle] then return true end diff --git a/modules/inventory/origen_inventory/server.lua b/modules/inventory/origen_inventory/server.lua index 19ec807..aa2224e 100644 --- a/modules/inventory/origen_inventory/server.lua +++ b/modules/inventory/origen_inventory/server.lua @@ -2,6 +2,7 @@ if GetResourceState('origen_inventory') ~= 'started' then return end Inventory = Inventory or {} +Inventory.Stashes = Inventory.Stashes or {} local origin = exports.origen_inventory @@ -29,6 +30,52 @@ Inventory.RemoveItem = function(src, item, count, slot, metadata) return origin:removeItem(src, item, count, metadata, slot, true) end +---This will add items to a trunk, and return true or false based on success +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + local id = "trunk_"..identifier + if type(items) ~= "table" then return false end + Inventory.RegisterStash(id, identifier, 20, 10000, nil, nil, nil) + local repack_items = {} + for _, v in pairs(items) do + table.insert(repack_items, { + name = v.item, + amount = v.count, + metadata = v.metadata or {} + }) + end + if #repack_items == 0 then return false end + origin:addItems(id, repack_items) + return true +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param identifier string +---@return boolean +Inventory.ClearStash = function(identifier, _type) + if type(identifier) ~= "string" then return false end + if Inventory.Stashes[identifier] then Inventory.Stashes[identifier] = nil end + local id = identifier + if _type == "trunk" then + id = "trunk_"..id + elseif _type == "glovebox" then + id = "glovebox_"..id + elseif _type == "stash" then + id = "stash_"..id + end + local inv = origin:getInventory(identifier, _type) + if not inv then return false end + local indexed = inv.inventory + for _, v in pairs(indexed) do + if v.slot then + origin:removeItem(id, v.name, v.amount, nil, v.slot) + end + end + return true +end + ---This will return a table with the item info, {name, label, stack, weight, description, image} ---@param item string ---@return table @@ -45,9 +92,7 @@ Inventory.GetItemInfo = function(item) } end - ---This will return the count of the item in the players inventory, if not found will return 0. ---- ---if metadata is passed it will find the matching items count. ---@param src number ---@param item string @@ -65,7 +110,6 @@ Inventory.GetPlayerInventory = function(src) end ---Returns the specified slot data as a table. ---- ---format {weight, name, metadata, slot, label, count} ---@param src number ---@param slot number @@ -99,20 +143,17 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - return origin:OpenInventory(src, 'stash', id) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] + return origin:OpenInventory(src, _type, id) end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -120,8 +161,20 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - return origin:registerStash(id, label, slots, weight, owner, groups, coords) + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + origin:registerStash(id, label, slots, weight, owner, groups, coords) + return true, id end ---This will return a boolean if the player has the item. @@ -174,11 +227,11 @@ Inventory.OpenShop = function(src, shopTitle) end -- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups) +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) return true, print("Currently runtime shops are not supported in origen_inventory") end diff --git a/modules/inventory/ox_inventory/server.lua b/modules/inventory/ox_inventory/server.lua index 6e3ec45..1bd2d3b 100644 --- a/modules/inventory/ox_inventory/server.lua +++ b/modules/inventory/ox_inventory/server.lua @@ -5,6 +5,7 @@ local ox_inventory = exports.ox_inventory local registeredShops = {} Inventory = Inventory or {} +Inventory.Stashes = Inventory.Stashes or {} ---This will add an item, and return true or false based on success ---@param src number @@ -30,6 +31,31 @@ Inventory.RemoveItem = function(src, item, count, slot, metadata) return ox_inventory:RemoveItem(src, item, count, metadata, slot) end +---This will add items to a trunk, and return true or false based on success +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + local id = "trunk"..identifier + if type(items) ~= "table" then return false end + Inventory.RegisterStash(id, identifier, 20, 10000, nil, nil, nil) + Wait(100) -- Wait for the stash to be registered just in case + for _, v in pairs(items) do + ox_inventory:AddItem(id, v.item, v.count, v.metadata) + end + return true +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + ox_inventory:ClearInventory(_type..id, nil) + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return true +end + ---This will return a table with the item info, {name, label, stack, weight, description, image} ---@param item string ---@return table @@ -86,20 +112,17 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - TriggerClientEvent('ox_inventory:openInventory', src, 'stash', 'stash_' .. id) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + --local tbl = Inventory.Stashes[id] + ox_inventory:forceOpenInventory(src, _type, id) end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -107,8 +130,20 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - return ox_inventory:RegisterStash(id, label, slots, weight, owner) + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + ox_inventory:RegisterStash(id, label, slots, weight, owner, groups) + return true, id end ---This will return a boolean if the player has the item. @@ -156,11 +191,11 @@ Inventory.OpenShop = function(src, shopTitle) end -- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups) +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) if registeredShops[shopTitle] then return true end registeredShops[shopTitle] = true ox_inventory:RegisterShop(shopTitle, { name = shopTitle, inventory = shopInventory, groups = shopGroups, }) @@ -169,12 +204,9 @@ Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups end - ---UNUSED: ---This will return generic item data from the specified inventory, with the items total count. ---- ---format without metadata { count, stack, name, weight, label } ---- ---fortmat with metadata { count, stack, name, weight, label, metadata } ---@param src number ---@param item string diff --git a/modules/inventory/ps-inventory/server.lua b/modules/inventory/ps-inventory/server.lua index 2dc105c..d6ba99e 100644 --- a/modules/inventory/ps-inventory/server.lua +++ b/modules/inventory/ps-inventory/server.lua @@ -4,6 +4,7 @@ local sloth = exports['ps-inventory'] local registeredShops = {} Inventory = Inventory or {} +Inventory.Stashes = Inventory.Stashes or {} ---This will add an item, and return true or false based on success ---@param src number @@ -31,6 +32,24 @@ Inventory.RemoveItem = function(src, item, count, slot, metadata) return sloth:RemoveItem(src, item, count, slot, 'community_bridge') end +---This will add items to a trunk, and return true or false based on success +---@param identifier string +---@param items table +---@return boolean +Inventory.AddItemsToTrunk = function(identifier, items) + if type(items) ~= "table" then return false end + return false, print("AddItemsToTrunk is not implemented in ps-inventory, because of this we dont have a way to add items to a trunk.") +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return false, print("ClearInventory is not implemented in ps-inventory, because of this we dont have a way to clear a stash.") +end + ---This will return a table with the item info, {name, label, stack, weight, description, image} ---@param item string ---@return table @@ -84,20 +103,17 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - TriggerClientEvent('community_bridge:client:ps-inventory:openStash', src, id, { label = label, maxweight = weight, slots = slots, }) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] + TriggerClientEvent('community_bridge:client:ps-inventory:openStash', src, id, { label = tbl.label, maxweight = tbl.weight, slots = tbl.slots, }) end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -105,8 +121,19 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - return true + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + return true, id end ---This will return a boolean if the player has the item. @@ -159,11 +186,11 @@ Inventory.OpenShop = function(src, shopTitle) end -- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(src, shopTitle, shopInventory, shopCoords, shopGroups) +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(src, shopTitle, shopInventory, shopCoords, shopGroups) if not shopTitle or not shopInventory or not shopCoords then return end if registeredShops[shopTitle] then return true end diff --git a/modules/inventory/qb-inventory/server.lua b/modules/inventory/qb-inventory/server.lua index 8df9850..cdefa7b 100644 --- a/modules/inventory/qb-inventory/server.lua +++ b/modules/inventory/qb-inventory/server.lua @@ -3,6 +3,7 @@ if GetResourceState('qb-inventory') ~= 'started' then return end local qbInventory = exports['qb-inventory'] Inventory = Inventory or {} +Inventory.Stashes = Inventory.Stashes or {} local registeredShops = {} local v1ShopData = {} @@ -22,7 +23,7 @@ end Inventory.AddItem = function(src, item, count, slot, metadata) TriggerClientEvent('qb-inventory:client:ItemBox', src, QBCore.Shared.Items[item], 'add', count) TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, {action = "add", item = item, count = count, slot = slot, metadata = metadata}) - return exports['qb-inventory']:AddItem(src, item, count, slot, metadata, 'community_bridge') + return qbInventory:AddItem(src, item, count, slot, metadata, 'community_bridge') end ---This will remove an item, and return true or false based on success @@ -35,7 +36,59 @@ end Inventory.RemoveItem = function(src, item, count, slot, metadata) TriggerClientEvent('qb-inventory:client:ItemBox', src, QBCore.Shared.Items[item], 'remove', count) TriggerClientEvent("community_bridge:client:inventory:updateInventory", src, {action = "remove", item = item, count = count, slot = slot, metadata = metadata}) - return exports['qb-inventory']:RemoveItem(src, item, count, slot, 'community_bridge') + return qbInventory:RemoveItem(src, item, count, slot, 'community_bridge') +end + +---This will add items to a trunk, and return true or false based on success +---If a trunk with the identifier does not exist, it will create one with default values. +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + if type(items) ~= "table" then return false end + local fullTrunkId = "trunk-"..identifier + local repacked_items = {} + local slot = 0 + for _, item in pairs(items) do + slot = slot + 1 + repacked_items[slot] = { + name = item.item, + amount = item.count, + info = item.metadata, + type = item.type or "item", + slot = slot, + } + end + local newVersion = getInventoryNewVersion() + if newVersion then + qbInventory:CreateInventory(fullTrunkId, { label = fullTrunkId }) + Wait(1000) + for i = 1, #repacked_items do + local v = repacked_items[i] + qbInventory:AddItem(fullTrunkId, v.name, v.amount, v.slot, v.info, "community_bridge, adding items to trunk") + end + else + -- I dont have a copy of this version to test it, if you run into issues please let me know. + TriggerEvent("inventory:server:addTrunkItems", fullTrunkId, repacked_items) + end + return true +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + if _type == "trunk" then + id = "trunk-"..id + elseif _type == "glovebox" then + id = "glovebox-"..id + end + if qbInventory:GetInventory(id) then + qbInventory:ClearStash(id) + end + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return true end ---This will return a table with the item info, {name, label, stack, weight, description, image} @@ -55,7 +108,6 @@ Inventory.GetItemInfo = function(item) end ---Returns the specified slot data as a table. ---- ---format {weight, name, metadata, slot, label, count} ---@param src number ---@param slot number @@ -77,20 +129,22 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - TriggerClientEvent('community_bridge:client:qb-inventory:openStash', src, id, { weight = weight, slots = slots }) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] + + if getInventoryNewVersion() then + return qbInventory:OpenInventory(src, id) + end + + TriggerClientEvent('community_bridge:client:qb-inventory:openStash', src, id, { weight = tbl.weight, slots = tbl.slots}) end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -98,8 +152,19 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - return true + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + return true, id end ---This will return a boolean if the player has the item. @@ -136,16 +201,16 @@ end Inventory.UpdatePlate = function(oldplate, newplate) local newVersion = getInventoryNewVersion() if newVersion then - local gloveboxInv = exports['qb-inventory']:GetInventory('glovebox-'..oldplate) or {slots = 5, maxweight = 10000, items = {}} + local gloveboxInv = qbInventory:GetInventory('glovebox-'..oldplate) or {slots = 5, maxweight = 10000, items = {}} local storedGloveBox = Bridge.Tables.DeepClone(gloveboxInv, nil, nil) - local trunkInv = exports['qb-inventory']:GetInventory('trunk-'..oldplate) or {slots = 5, maxweight = 10000, items = {}} + local trunkInv = qbInventory:GetInventory('trunk-'..oldplate) or {slots = 5, maxweight = 10000, items = {}} local storedTrunk = Bridge.Tables.DeepClone(trunkInv, nil, nil) - exports['qb-inventory']:ClearStash('glovebox-'..oldplate) - exports['qb-inventory']:ClearStash('trunk-'..oldplate) - exports['qb-inventory']:CreateInventory('glovebox-'..newplate, {label = 'glovebox-'..newplate, slots = storedGloveBox.slots, maxweight = storedGloveBox.maxweight}) - exports['qb-inventory']:SetInventory('glovebox-'..newplate, storedGloveBox.items, "Community Bridge Moving Items In GloveBox") - exports['qb-inventory']:CreateInventory('trunk-'..newplate, {label = 'trunk-'..newplate, slots = storedTrunk.slots, maxweight = storedTrunk.maxweight}) - exports['qb-inventory']:SetInventory('trunk-'..newplate, storedTrunk.items, "Community Bridge Moving Items In Trunk") + qbInventory:ClearStash('glovebox-'..oldplate) + qbInventory:ClearStash('trunk-'..oldplate) + qbInventory:CreateInventory('glovebox-'..newplate, {label = 'glovebox-'..newplate, slots = storedGloveBox.slots, maxweight = storedGloveBox.maxweight}) + qbInventory:SetInventory('glovebox-'..newplate, storedGloveBox.items, "Community Bridge Moving Items In GloveBox") + qbInventory:CreateInventory('trunk-'..newplate, {label = 'trunk-'..newplate, slots = storedTrunk.slots, maxweight = storedTrunk.maxweight}) + qbInventory:SetInventory('trunk-'..newplate, storedTrunk.items, "Community Bridge Moving Items In Trunk") return true else local queries = { @@ -159,13 +224,13 @@ Inventory.UpdatePlate = function(oldplate, newplate) return true, exports["jg-mechanic"]:vehiclePlateUpdated(oldplate, newplate) end --- This will open the specified shop for the src passed. +---This will open the specified shop for the src passed. ---@param src number ---@param shopTitle string Inventory.OpenShop = function(src, shopTitle) local newVersion = getInventoryNewVersion() if newVersion then - return exports['qb-inventory']:OpenShop(src, shopTitle) + return qbInventory:OpenShop(src, shopTitle) else local shopData = v1ShopData[shopTitle] if not shopData then return false end @@ -173,13 +238,13 @@ Inventory.OpenShop = function(src, shopTitle) end end --- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(src, shopTitle, shopInventory, shopCoords, shopGroups) - if not shopTitle or not shopInventory or not shopCoords then return end +--This will register a shop, if it already exists it will return true. +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) + if not shopTitle or not shopInventory then return end if registeredShops[shopTitle] then return true end registeredShops[shopTitle] = true local newVersion = getInventoryNewVersion() @@ -188,7 +253,7 @@ Inventory.CreateShop = function(src, shopTitle, shopInventory, shopCoords, shopG for _, v in pairs(shopInventory) do table.insert(repackedShopItems, {name = v.name, price = v.price, amount = v.count or 1000}) end - exports['qb-inventory']:CreateShop({ name = shopTitle, label = shopTitle, coords = shopCoords, items = repackedShopItems, }) + qbInventory:CreateShop({ name = shopTitle, label = shopTitle, coords = shopCoords, items = repackedShopItems, }) return true else local shopData = { label = shopTitle, items = {}, slots = 0 } @@ -198,7 +263,7 @@ Inventory.CreateShop = function(src, shopTitle, shopInventory, shopCoords, shopG end shopData.slots = #shopData.items - TriggerClientEvent("inventory:client:OpenInventory", src, "shop", shopTitle, shopData) + -- TriggerClientEvent("inventory:client:OpenInventory", src, "shop", shopTitle, shopData) v1ShopData[shopTitle] = shopData print("QB-INVENTORY: You are using an outdated version of qb-inventory, please update to the latest version. Stuff will still work but you are using litterally the most exploitable inventory in fivem.") end diff --git a/modules/inventory/qs-inventory/server.lua b/modules/inventory/qs-inventory/server.lua index ddb2d3b..f29fe20 100644 --- a/modules/inventory/qs-inventory/server.lua +++ b/modules/inventory/qs-inventory/server.lua @@ -4,6 +4,7 @@ if GetResourceState('qs-inventory') ~= 'started' then return end local quasar = exports['qs-inventory'] Inventory = Inventory or {} +Inventory.Stashes = Inventory.Stashes or {} ---This will add an item, and return true or false based on success ---@param src number @@ -30,6 +31,41 @@ Inventory.RemoveItem = function(src, item, count, slot, metadata) return quasar:RemoveItem(src, item, count, slot, metadata) end +---This will add items to a trunk, and return true or false based on success +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + if type(items) ~= "table" then return false end + return false + --[[ + for k, v in pairs(items) do + -- + In testing this inventory allowed it on owned vehicle but not unowned vehicles, + also attempted registering it as a stash with no luck. + was thinking about just forcing it in sql but there is data attached that I assume is a timestamp + kinda not sure on this one atm... + Also there is no GetInventory(identifier) only by player source + --quasar:AddToTrunk(identifier, v.count, v.metadata, v.item, v.metadata) + end + return true + --]] +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return false + --[[ + quasar:ClearOtherInventory(_type, id) + + return true + --]] +end + ---This will return a table with the item info, {name, label, stack, weight, description, image} ---@param item string ---@return table @@ -113,21 +149,18 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - TriggerEvent("inventory:server:OpenInventory", "stash", id, { maxweight = weight, slots = slots }) +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] + TriggerEvent("inventory:server:OpenInventory", _type, id, tbl and { maxweight = tbl.weight, slots = tbl.slots }) TriggerClientEvent("inventory:client:SetCurrentStash",src, id) end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -135,9 +168,19 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - --exports['qs-inventory']:RegisterStash(src, id, stashSlots, stashWeight) -- this needs to pass source to register, need to plan around this. - return true + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + return true, id end ---This will return a boolean if the player has the item. @@ -192,11 +235,11 @@ Inventory.OpenShop = function(src, shopTitle) end -- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups) +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) return false, print("Currently qs shop is not bridged") end diff --git a/modules/inventory/tgiann-inventory/server.lua b/modules/inventory/tgiann-inventory/server.lua index f72cff6..ecca9a0 100644 --- a/modules/inventory/tgiann-inventory/server.lua +++ b/modules/inventory/tgiann-inventory/server.lua @@ -4,6 +4,7 @@ if GetResourceState('tgiann-inventory') ~= 'started' then return end local tgiann = exports["tgiann-inventory"] Inventory = Inventory or {} +Inventory.Stashes = Inventory.Stashes or {} ---This will add an item, and return true or false based on success ---@param src number @@ -104,20 +105,17 @@ end ---This will open the specified stash for the src passed. ---@param src number +---@param _type string ---@param id number||string ----@param label string ----@param slots number ----@param weight number ----@param owner string ----@param groups table ----@param coords table ---@return nil -Inventory.OpenStash = function(src, id, label, slots, weight, owner, groups, coords) - print("Currently not bridged for stashes") +Inventory.OpenStash = function(src, _type, id) + _type = _type or "stash" + local tbl = Inventory.Stashes[id] + return tgiann:ForceOpenInventory(src, _type, id, tbl and { maxWeight = tbl.weight , slots = tbl.slot, label = tbl.label}) end ---This will register a stash ----@param id number||string +---@param id number|string ---@param label string ---@param slots number ---@param weight number @@ -125,8 +123,19 @@ end ---@param groups table ---@param coords table ---@return boolean +---@return string|number Inventory.RegisterStash = function(id, label, slots, weight, owner, groups, coords) - return false, print("Currently not bridged for stashes") + if Inventory.Stashes[id] then return true, id end + Inventory.Stashes[id] = { + id = id, + label = label, + slots = slots, + weight = weight, + owner = owner, + groups = groups, + coords = coords + } + return true, id end ---This will return a boolean if the player has the item. @@ -157,10 +166,34 @@ Inventory.UpdatePlate = function(oldplate, newplate) } local values = { newplate = newplate, oldplate = oldplate } MySQL.transaction.await(queries, values) + tgiann:UpdateVehicle(oldplate, newplate) if GetResourceState('jg-mechanic') ~= 'started' then return true end return true, exports["jg-mechanic"]:vehiclePlateUpdated(oldplate, newplate) end +---This will add items to a trunk, and return true or false based on success +---@param identifier string +---@param items table +---@return boolean +Inventory.AddTrunkItems = function(identifier, items) + local id = "trunk"..identifier + if type(items) ~= "table" then return false end + for _, v in pairs(items) do + tgiann:AddItemToSecondaryInventory("trunk", identifier, v.item, v.count, nil, v.metadata) + end + return true +end + +---This will clear the specified inventory, will always return true unless a value isnt passed correctly. +---@param id string +---@return boolean +Inventory.ClearStash = function(id, _type) + if type(id) ~= "string" then return false end + tgiann:DeleteInventory(_type, id) + if Inventory.Stashes[id] then Inventory.Stashes[id] = nil end + return true +end + ---This will get the image path for an item, it is an alternate option to GetItemInfo. If a image isnt found will revert to community_bridge logo (useful for menus) ---@param item string ---@return string @@ -177,15 +210,15 @@ end ---@param src number ---@param shopTitle string Inventory.OpenShop = function(src, shopTitle) - print("Currently tgiann-inventory is not bridged for shops") + return false, print("Currently tgiann-inventory is not bridged for shops") end -- This will register a shop, if it already exists it will return true. --- @param shopTitle string --- @param shopInventory table --- @param shopCoords table --- @param shopGroups table -Inventory.CreateShop = function(shopTitle, shopInventory, shopCoords, shopGroups) +---@param shopTitle string +---@param shopInventory table +---@param shopCoords table +---@param shopGroups table +Inventory.RegisterShop = function(shopTitle, shopInventory, shopCoords, shopGroups) return false, print("Currently tgiann-inventory is not bridged for shops") end diff --git a/modules/managment/Renewed-Banking/server.lua b/modules/managment/Renewed-Banking/server.lua deleted file mode 100644 index a4683fb..0000000 --- a/modules/managment/Renewed-Banking/server.lua +++ /dev/null @@ -1,27 +0,0 @@ -if GetResourceState('Renewed-Banking') ~= 'started' then return end -Managment = Managment or {} - ----This will return a table with account details ----@param account string ----@return table -Managment.GetAccountMoney = function(account) - return exports['Renewed-Banking']:getAccountMoney(account) -end - ----This will add money to the specified account of the passed amount ----@param account string ----@param amount number ----@return boolean -Managment.AddAccountMoney = function(account, amount) - return exports['Renewed-Banking']:addAccountMoney(account, amount) -end - ----This will remove money from the specified account of the passed amount ----@param account string ----@param amount number ----@return boolean -Managment.RemoveAccountMoney = function(account, amount) - return exports['Renewed-Banking']:removeAccountMoney(account, amount) -end - -return Managment \ No newline at end of file diff --git a/modules/managment/_default/server.lua b/modules/managment/_default/server.lua index 80cf953..ba069b9 100644 --- a/modules/managment/_default/server.lua +++ b/modules/managment/_default/server.lua @@ -1,14 +1,34 @@ +---@diagnostic disable: duplicate-set-field Managment = Managment or {} +---This will get the name of the Managment system being being used. +---@return string +Managment.GetManagmentName = function() + return 'default' +end + +---This will return a table with account details +---@param account string +---@return table Managment.GetAccountMoney = function(account) + return {}, print("The resource you are using does not support this function.") +end + +---This will add money to the specified account of the passed amount +---@param account string +---@param amount number +---@param reason string +---@return boolean +Managment.AddAccountMoney = function(account, amount, reason) return false, print("The resource you are using does not support this function.") end -Managment.AddAccountMoney = function(account, amount) - return false, print("The resource you are using does not support this function.") -end - -Managment.RemoveAccountMoney = function(account, amount) +---This will remove money from the specified account of the passed amount +---@param account string +---@param amount number +---@param reason string +---@return boolean +Managment.RemoveAccountMoney = function(account, amount, reason) return false, print("The resource you are using does not support this function.") end diff --git a/modules/managment/fd_banking/server.lua b/modules/managment/fd_banking/server.lua new file mode 100644 index 0000000..582b86e --- /dev/null +++ b/modules/managment/fd_banking/server.lua @@ -0,0 +1,38 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('fd_banking') == 'missing' then return end +Managment = Managment or {} + +local fd_banking = exports['fd_banking'] + +---This will get the name of the Managment system being being used. +---@return string +Managment.GetManagmentName = function() + return 'fd_banking' +end + +---This will return a table with account details +---@param account string +---@return table +Managment.GetAccountMoney = function(account) + return fd_banking:GetAccount(account) +end + +---This will add money to the specified account of the passed amount +---@param account string +---@param amount number +---@param reason string +---@return boolean +Managment.AddAccountMoney = function(account, amount, reason) + return fd_banking:AddMoney(account, amount, reason) +end + +---This will remove money from the specified account of the passed amount +---@param account string +---@param amount number +---@param reason string +---@return boolean +Managment.RemoveAccountMoney = function(account, amount, reason) + return fd_banking:RemoveMoney(account, amount, reason) +end + +return Managment \ No newline at end of file diff --git a/modules/managment/okokBanking/server.lua b/modules/managment/okokBanking/server.lua index 60a32b4..c2fc583 100644 --- a/modules/managment/okokBanking/server.lua +++ b/modules/managment/okokBanking/server.lua @@ -1,27 +1,38 @@ -if GetResourceState('okokBanking') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('okokBanking') == 'missing' then return end Managment = Managment or {} +local okokBanking = exports['okokBanking'] + +---This will get the name of the Managment system being being used. +---@return string +Managment.GetManagmentName = function() + return 'okokBanking' +end + ---This will return a table with account details ---@param account string ---@return table Managment.GetAccountMoney = function(account) - return exports['okokBanking']:GetAccount(account) + return okokBanking:GetAccount(account) end ---This will add money to the specified account of the passed amount ---@param account string ---@param amount number +---@param _ string ---@return boolean -Managment.AddAccountMoney = function(account, amount) - return exports['okokBanking']:AddMoney(account, amount) +Managment.AddAccountMoney = function(account, amount, _) + return okokBanking:AddMoney(account, amount) end ---This will remove money from the specified account of the passed amount ---@param account string ---@param amount number +---@param _ string ---@return boolean -Managment.RemoveAccountMoney = function(account, amount) - return exports['okokBanking']:RemoveMoney(account, amount) +Managment.RemoveAccountMoney = function(account, amount, _) + return okokBanking:RemoveMoney(account, amount) end return Managment \ No newline at end of file diff --git a/modules/managment/qb-banking/server.lua b/modules/managment/qb-banking/server.lua index da26df1..59d47fd 100644 --- a/modules/managment/qb-banking/server.lua +++ b/modules/managment/qb-banking/server.lua @@ -1,27 +1,38 @@ -if GetResourceState('qb-banking') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('qb-banking') == 'missing' then return end Managment = Managment or {} +local qbBanking = exports['qb-banking'] + +---This will get the name of the Managment system being being used. +---@return string +Managment.GetManagmentName = function() + return 'qb-banking' +end + ---This will return a table with account details ---@param account string ---@return table Managment.GetAccountMoney = function(account) - return exports['qb-banking']:GetAccountBalance(account) + return qbBanking:GetAccountBalance(account) end ---This will add money to the specified account of the passed amount ---@param account string ---@param amount number +---@param reason string ---@return boolean -Managment.AddAccountMoney = function(account, amount) - return exports['qb-banking']:AddMoney(account, amount) +Managment.AddAccountMoney = function(account, amount, reason) + return qbBanking:AddMoney(account, amount, reason) end ---This will remove money from the specified account of the passed amount ---@param account string ---@param amount number +---@param reason string ---@return boolean -Managment.RemoveAccountMoney = function(account, amount) - return exports['qb-banking']:RemoveMoney(account, amount) +Managment.RemoveAccountMoney = function(account, amount, reason) + return qbBanking:RemoveMoney(account, amount, reason) end return Managment \ No newline at end of file diff --git a/modules/managment/renewed-banking/server.lua b/modules/managment/renewed-banking/server.lua new file mode 100644 index 0000000..0f6e747 --- /dev/null +++ b/modules/managment/renewed-banking/server.lua @@ -0,0 +1,38 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('Renewed-Banking') == 'missing' then return end +Managment = Managment or {} + +local renewed = exports['Renewed-Banking'] + +---This will get the name of the Managment system being being used. +---@return string +Managment.GetManagmentName = function() + return 'Renewed-Banking' +end + +---This will return a table with account details +---@param account string +---@return table +Managment.GetAccountMoney = function(account) + return renewed:getAccountMoney(account) +end + +---This will add money to the specified account of the passed amount +---@param account string +---@param amount number +---@param _ string +---@return boolean +Managment.AddAccountMoney = function(account, amount, _) + return renewed:addAccountMoney(account, amount) +end + +---This will remove money from the specified account of the passed amount +---@param account string +---@param amount number +---@param _ string +---@return boolean +Managment.RemoveAccountMoney = function(account, amount, _) + return renewed:removeAccountMoney(account, amount) +end + +return Managment \ No newline at end of file diff --git a/modules/managment/tgiann-bank/server.lua b/modules/managment/tgiann-bank/server.lua new file mode 100644 index 0000000..7d79137 --- /dev/null +++ b/modules/managment/tgiann-bank/server.lua @@ -0,0 +1,38 @@ +---@diagnostic disable: duplicate-set-field +if GetResourceState('tgiann-bank') == 'missing' then return end +Managment = Managment or {} + +local tgiann = exports["tgiann-bank"] + +---This will get the name of the Managment system being being used. +---@return string +Managment.GetManagmentName = function() + return 'tgiann-bank' +end + +---This will return a table with account details +---@param account string +---@return table +Managment.GetAccountMoney = function(account) + return tgiann:GetJobAccountBalance(account) +end + +---This will add money to the specified account of the passed amount +---@param account string +---@param amount number +---@param _ string +---@return boolean +Managment.AddAccountMoney = function(account, amount, _) + return tgiann:AddJobMoney(account, amount) +end + +---This will remove money from the specified account of the passed amount +---@param account string +---@param amount number +---@param _ string +---@return boolean +Managment.RemoveAccountMoney = function(account, amount, _) + return tgiann:RemoveJobMoney(account, amount) +end + +return Managment \ No newline at end of file diff --git a/modules/menu/_oxlib.lua b/modules/menu/_oxlib.lua index c1e78cf..02603fe 100644 --- a/modules/menu/_oxlib.lua +++ b/modules/menu/_oxlib.lua @@ -2,7 +2,8 @@ local resourceName = "ox_lib" local configValue = BridgeClientConfig.MenuSystem if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end Menus = Menus or {} ---- Converts a QB menu to an Ox menu. + +---Converts a QB menu to an Ox menu. ---@param id string The menu ID. ---@param menu table The QB menu data. ---@return table The Ox menu data. @@ -50,4 +51,4 @@ OpenMenu = function(id, data, useQBinput) lib.registerContext(data) lib.showContext(id) return data -end +end \ No newline at end of file diff --git a/modules/menu/_qb-menu.lua b/modules/menu/_qb-menu.lua index 411fd0e..98285bb 100644 --- a/modules/menu/_qb-menu.lua +++ b/modules/menu/_qb-menu.lua @@ -1,8 +1,8 @@ local resourceName = "qb-menu" local configValue = BridgeClientConfig.MenuSystem if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ---print("Loading QB Menu") ---- Converts an Ox menu to a QB menu. + +---Converts an Ox menu to a QB menu. ---@param id string The menu ID. ---@param menu table The Ox menu data. ---@return table The QB menu data. diff --git a/modules/menu/client.lua b/modules/menu/client.lua index 26b2713..c5a497f 100644 --- a/modules/menu/client.lua +++ b/modules/menu/client.lua @@ -1,7 +1,7 @@ Menus = Menus or {} Menu = {} ---- Opens a menu based on the configuration. +---Opens a menu based on the configuration. ---@param data table The menu data. ---@param useQb boolean Whether to use QB menu syntax. ---@return id string The menu ID. @@ -12,9 +12,9 @@ function Menu.Open(data, useQb) return id end ---- Event to handle callback from menu selection. ---- @param _args table The arguments passed to the callback. ---- @return nil +---Event to handle callback from menu selection. +---@param _args table The arguments passed to the callback. +---@return nil RegisterNetEvent('community_bridge:client:MenuCallback', function(_args) local id = _args.id local onSelect = _args.onSelect @@ -23,91 +23,4 @@ RegisterNetEvent('community_bridge:client:MenuCallback', function(_args) onSelect(args) end) -return Menu - ---[[ - ---Unit Tests -local qbMenu = { - { - header = 'QBCore Test Menu', - icon = 'fas fa-code', - isMenuHeader = true, -- Set to true to make a nonclickable title - }, - { - header = 'First Button', - txt = 'Open a secondary menu!', - icon = 'fas fa-code-pull-request', - -- disabled = false, -- optional, non-clickable and grey scale - -- hidden = true, -- optional, hides the button completely - params = { - -- isServer = false, -- optional, specify event type - event = 'community_bridge:client:TestEvent', - args = { - number = 1, - } - } - }, - { - header = 'Second Button', - txt = 'Open a secondary menu!', - icon = 'fas fa-code-pull-request', - params = { - event = 'community_bridge:client:TestEvent', - args = { - number = 2, - } - } - } -} - -local oxMenu = { - id = "test", - title = "Test Menu", - options = { - { - title = "First Button", - description = "Open a secondary menu!", - icon = "fas fa-code-pull-request", - args = { - number = 1, - }, - onSelect = function(selected, secondary, args) - print("Selected", json.encode(selected)) - end - }, - { - title = "Second Button", - description = "Open a secondary menu!", - icon = "fas fa-code-pull-request", - args = { - number = 2, - }, - onSelect = function(selected, secondary, args) - print("Selected", json.encode(selected)) - end - } - } -} - -RegisterCommand("testmenu-qbtoox", function() - Menu.Open(qbMenu, true) -end) - -RegisterCommand("testmenu-oxtoqb", function() - Menu.Open(oxMenu, false) -end) - -RegisterCommand("testmenu-oxtoox", function() - Menu.Open(oxMenu, false) -end) - -RegisterCommand("testmenu-qbtoqb", function() - Menu.Open(qbMenu, true) -end) - -RegisterNetEvent('community_bridge:client:TestEvent', function(args) - print("Test Event", json.encode(args)) -end) - ---]] \ No newline at end of file +return Menu \ No newline at end of file diff --git a/modules/notify/_default/client.lua b/modules/notify/_default/client.lua index 72a5c40..7aef40d 100644 --- a/modules/notify/_default/client.lua +++ b/modules/notify/_default/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} ----@diagnostic disable-next-line: duplicate-set-field Notify.GetResourceName = function() return "none" end @@ -10,7 +10,6 @@ end ---@param _type string ---@param time number ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(message, _type, time) time = time or 3000 return Framework.Notify(message, nil, time) @@ -21,10 +20,8 @@ RegisterNetEvent('community_bridge:Client:Notify', function(message, _type, time end) ---------[[Depricated Stuff Below, please adjust to the HelpText module instead]]-------- - ---Depricated: This will hide the help text message on the screen ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.HideHelpText = function() return HelpText.HideHelpText() end @@ -32,7 +29,6 @@ end ---Depricated: This will show a help text message at the screen position passed ---@param message string ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.ShowHelpText = function(message, position) return HelpText.ShowHelpText(message, position) end diff --git a/modules/notify/_default/server.lua b/modules/notify/_default/server.lua index a6f5d41..fab0ddc 100644 --- a/modules/notify/_default/server.lua +++ b/modules/notify/_default/server.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} ---This will send a notification to the specified player of the passed message and type @@ -5,29 +6,21 @@ Notify = Notify or {} ---@param message string ---@param _type string ---@param time number ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(src, message, _type, time) TriggerClientEvent('community_bridge:Client:Notify', src, message, _type, time) end - - ---------[[Depricated Stuff Below, please adjust to the HelpText module instead]]-------- ---- ---- ---- ---Depricated -- This will show a help text message to the specified player at the screen position passed ---@param src number ---@param message string ---@param position string ----@diagnostic disable-next-line: duplicate-set-field Notify.ShowHelpText = function(src, message, position) return HelpText.ShowHelpText(src, message, position) end ---Depricated -- This will hide the help text message on the screen for the specified player ---@param src number ----@diagnostic disable-next-line: duplicate-set-field Notify.HideHelpText = function(src) return HelpText.HideHelpText(src) end diff --git a/modules/notify/mythic_notify/client.lua b/modules/notify/mythic_notify/client.lua index b276ef5..0538d61 100644 --- a/modules/notify/mythic_notify/client.lua +++ b/modules/notify/mythic_notify/client.lua @@ -1,9 +1,9 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} local resourceName = "mythic_notify" local configValue = BridgeSharedConfig.Notify if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field Notify.GetResourceName = function() return resourceName end @@ -13,7 +13,6 @@ end ---@param _type string ---@param time number ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(message, _type, time) time = time or 3000 return exports['mythic_notify']:SendAlert('inform', message, time) diff --git a/modules/notify/okokNotify/client.lua b/modules/notify/okokNotify/client.lua index 6375bab..1a158ea 100644 --- a/modules/notify/okokNotify/client.lua +++ b/modules/notify/okokNotify/client.lua @@ -1,9 +1,9 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} local resourceName = "okokNotify" local configValue = BridgeSharedConfig.Notify if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field Notify.GetResourceName = function() return resourceName end @@ -13,7 +13,6 @@ end ---@param _type string ---@param time number ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(message, _type, time) time = time or 3000 return exports['okokNotify']:Alert('Notification', message, time, _type, false) diff --git a/modules/notify/ox_lib/client.lua b/modules/notify/ox_lib/client.lua index 037dc95..83406d7 100644 --- a/modules/notify/ox_lib/client.lua +++ b/modules/notify/ox_lib/client.lua @@ -1,10 +1,10 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} local resourceName = "ox_lib" local configValue = BridgeSharedConfig.Notify if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field Notify.GetResourceName = function() return resourceName end @@ -14,7 +14,6 @@ end ---@param _type string ---@param time number ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(message, _type, time) time = time or 3000 return exports.ox_lib:notify({ description = message, type = _type, position = 'center-left' }) diff --git a/modules/notify/pNotify/client.lua b/modules/notify/pNotify/client.lua index 7cbf356..a79f24b 100644 --- a/modules/notify/pNotify/client.lua +++ b/modules/notify/pNotify/client.lua @@ -1,9 +1,9 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} local resourceName = "pNotify" local configValue = BridgeSharedConfig.Notify if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field Notify.GetResourceName = function() return resourceName end @@ -13,7 +13,6 @@ end ---@param _type string ---@param time number ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(message, _type, time) time = time or 3000 return exports['pNotify']:SendNotification({ text = message, type = _type, timeout = time, layout = 'centerRight' }) diff --git a/modules/notify/r_notify/client.lua b/modules/notify/r_notify/client.lua index 4b12e9e..d8305a8 100644 --- a/modules/notify/r_notify/client.lua +++ b/modules/notify/r_notify/client.lua @@ -1,9 +1,9 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} local resourceName = "r_notify" local configValue = BridgeSharedConfig.Notify if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field Notify.GetResourceName = function() return resourceName end @@ -13,7 +13,6 @@ end ---@param _type string ---@param time number ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(message, _type, time) time = time or 3000 return exports.r_notify:notify({title = 'Notification', content = message, type = _type, icon = "fas fa-check", duration = time, position = 'top-right', sound = false}) diff --git a/modules/notify/t-notify/client.lua b/modules/notify/t-notify/client.lua index 0dcc4c4..3c452c0 100644 --- a/modules/notify/t-notify/client.lua +++ b/modules/notify/t-notify/client.lua @@ -1,9 +1,9 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} local resourceName = "t-notify" local configValue = BridgeSharedConfig.Notify if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field Notify.GetResourceName = function() return resourceName end @@ -13,7 +13,6 @@ end ---@param _type string ---@param time number ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(message, _type, time) time = time or 3000 return exports['t-notify']:Alert({ style = 'info', message = message, duration = time, }) diff --git a/modules/notify/wasabi_notify/client.lua b/modules/notify/wasabi_notify/client.lua index f4d83f5..7fe692f 100644 --- a/modules/notify/wasabi_notify/client.lua +++ b/modules/notify/wasabi_notify/client.lua @@ -1,9 +1,9 @@ +---@diagnostic disable: duplicate-set-field Notify = Notify or {} local resourceName = "wasabi_notify" local configValue = BridgeSharedConfig.Notify if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field Notify.GetResourceName = function() return resourceName end @@ -13,7 +13,6 @@ end ---@param _type string ---@param time number ---@return nil ----@diagnostic disable-next-line: duplicate-set-field Notify.SendNotify = function(message, _type, time) time = time or 3000 return exports.wasabi_notify:notify(_type, message, time, _type) diff --git a/modules/phone/_default/client.lua b/modules/phone/_default/client.lua index b05bde5..bd3d2fe 100644 --- a/modules/phone/_default/client.lua +++ b/modules/phone/_default/client.lua @@ -1,6 +1,17 @@ +---@diagnostic disable: duplicate-set-field Phone = Phone or {} ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return 'default' +end + +---This will send an email to the passed email address with the title and message. +---@param email string +---@param title string +---@param message string +---@return boolean Phone.SendEmail = function(email, title, message) return false, Print.Error('There Is No Phone Bridged.') end diff --git a/modules/phone/_default/server.lua b/modules/phone/_default/server.lua index 899d30e..01bb488 100644 --- a/modules/phone/_default/server.lua +++ b/modules/phone/_default/server.lua @@ -1,11 +1,25 @@ +---@diagnostic disable: duplicate-set-field Phone = Phone or {} ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return 'default' +end + +---This will get the phone number of the passed source. +---@param src number +---@return number|boolean Phone.GetPlayerPhone = function(src) return false, Print.Error('There Is No Phone Bridged.') end ----@diagnostic disable-next-line: duplicate-set-field +---This will send an email to the passed source, email address, title and message. +---@param src number +---@param email string +---@param title string +---@param message string +---@return boolean Phone.SendEmail = function(src, email, title, message) return false, Print.Error('There Is No Phone Bridged.') end diff --git a/modules/phone/gksphone/client.lua b/modules/phone/gksphone/client.lua index ead89bb..f253028 100644 --- a/modules/phone/gksphone/client.lua +++ b/modules/phone/gksphone/client.lua @@ -1,15 +1,20 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "gksphone" -local configValue = BridgeSharedConfig.Phone -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end Phone = Phone or {} ----comment +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return resourceName +end + +---This will send an email to the passed email address with the title and message. ---@param email string ---@param title string ---@param message string ---@return boolean ----@diagnostic disable-next-line: duplicate-set-field Phone.SendEmail = function(email, title, message) return exports["gksphone"]:SendNewMail({ sender = email, image = '/html/static/img/icons/mail.png', subject = title, message = message }) end diff --git a/modules/phone/gksphone/server.lua b/modules/phone/gksphone/server.lua index 8d72d62..4efc6db 100644 --- a/modules/phone/gksphone/server.lua +++ b/modules/phone/gksphone/server.lua @@ -1,23 +1,27 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "gksphone" -local configValue = BridgeSharedConfig.Phone -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end Phone = Phone or {} ----comment +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return resourceName +end + +---This will get the phone number of the passed source. ---@param src number ----@return number| boolean ----@diagnostic disable-next-line: duplicate-set-field +---@return number|boolean Phone.GetPlayerPhone = function(src) return exports["gksphone"]:GetPhoneBySource(src) or false end ----comment +---This will send an email to the passed source, email address, title and message. ---@param src number ---@param email string ---@param title string ---@param message string ---@return boolean ----@diagnostic disable-next-line: duplicate-set-field Phone.SendEmail = function(src, email, title, message) local data = {} data.sender = email diff --git a/modules/phone/lb-phone/client.lua b/modules/phone/lb-phone/client.lua index 450f364..6a0cccc 100644 --- a/modules/phone/lb-phone/client.lua +++ b/modules/phone/lb-phone/client.lua @@ -1,14 +1,19 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "lb-phone" -local configValue = BridgeSharedConfig.Phone -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end Phone = Phone or {} ----comment +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return resourceName +end + +---This will send an email to the passed email address with the title and message. ---@param email string ---@param title string ---@param message string ----@return nil ----@diagnostic disable-next-line: duplicate-set-field +---@return boolean Phone.SendEmail = function(email, title, message) TriggerServerEvent('community_bridge:Server:genericEmail', {email = email, title = title, message = message}) end diff --git a/modules/phone/lb-phone/server.lua b/modules/phone/lb-phone/server.lua index 6545f23..0bedbe6 100644 --- a/modules/phone/lb-phone/server.lua +++ b/modules/phone/lb-phone/server.lua @@ -1,20 +1,27 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "lb-phone" -local configValue = BridgeSharedConfig.Phone -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end Phone = Phone or {} ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return resourceName +end + +---This will get the phone number of the passed source. +---@param src number +---@return number|boolean Phone.GetPlayerPhone = function(src) return exports["lb-phone"]:GetEquippedPhoneNumber(src) or false end ----comment +---This will send an email to the passed source, email address, title and message. ---@param src number ---@param email string ---@param title string ---@param message string ---@return boolean ----@diagnostic disable-next-line: duplicate-set-field Phone.SendEmail = function(src, email, title, message) local numberNumber = exports["lb-phone"]:GetEquippedPhoneNumber(src) if not numberNumber then return false, Prints.Error("Could not Find Phone number") end diff --git a/modules/phone/okokPhone/client.lua b/modules/phone/okokPhone/client.lua index c6fd86d..0472ca7 100644 --- a/modules/phone/okokPhone/client.lua +++ b/modules/phone/okokPhone/client.lua @@ -1,15 +1,19 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "okokPhone" -local configValue = BridgeSharedConfig.Phone -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end Phone = Phone or {} ----comment +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return resourceName +end + +---This will send an email to the passed email address with the title and message. ---@param email string ---@param title string ---@param message string ---@return boolean ----@diagnostic disable-next-line: duplicate-set-field Phone.SendEmail = function(email, title, message) --<-- TODO swap to internal callback system local success = lib.callback.await('community_bridge:Callback:okokPhone:sendEmail', false, email, title, message) --[[ @as boolean ]] diff --git a/modules/phone/okokPhone/server.lua b/modules/phone/okokPhone/server.lua index d493309..1ec524d 100644 --- a/modules/phone/okokPhone/server.lua +++ b/modules/phone/okokPhone/server.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field ---@class NewEmail ---@field sender string ---@field recipients string[] @@ -14,25 +15,28 @@ ---@field data any local resourceName = "okokPhone" -local configValue = BridgeSharedConfig.Phone -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end Phone = Phone or {} ----comment +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return resourceName +end + +---This will get the phone number of the passed source. ---@param src number ----@return number| boolean ----@diagnostic disable-next-line: duplicate-set-field +---@return number|boolean Phone.GetPlayerPhone = function(src) return exports.okokPhone:getPhoneNumberFromSource(src) or false end ----comment +---This will send an email to the passed source, email address, title and message. ---@param src number ---@param email string ---@param title string ---@param message string ---@return boolean ----@diagnostic disable-next-line: duplicate-set-field Phone.SendEmail = function(src, email, title, message) local senderAddress = exports.okokPhone:getEmailAddressFromSource(src) --[[ @as string? ]] if not senderAddress then return false end diff --git a/modules/phone/qs-smartphone/client.lua b/modules/phone/qs-smartphone/client.lua index f0466a3..72b1cda 100644 --- a/modules/phone/qs-smartphone/client.lua +++ b/modules/phone/qs-smartphone/client.lua @@ -1,14 +1,19 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "qs-smartphone" -local configValue = BridgeSharedConfig.Phone -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end Phone = Phone or {} ----comment +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return resourceName +end + +---This will send an email to the passed email address with the title and message. ---@param email string ---@param title string ---@param message string ----@return nil ----@diagnostic disable-next-line: duplicate-set-field +---@return boolean Phone.SendEmail = function(email, title, message) return true, TriggerServerEvent('qs-smartphone:server:sendNewMail', { sender = email, subject = title, message = message, button = {} }) end diff --git a/modules/phone/qs-smartphone/server.lua b/modules/phone/qs-smartphone/server.lua index 792674a..fbcc6c9 100644 --- a/modules/phone/qs-smartphone/server.lua +++ b/modules/phone/qs-smartphone/server.lua @@ -1,17 +1,22 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "qs-smartphone" -local configValue = BridgeSharedConfig.Phone -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end Phone = Phone or {} ----comment +---This will get the name of the Phone system being being used. +---@return string +Phone.GetPhoneName = function() + return resourceName +end + +---This will get the phone number of the passed source. ---@param src number ----@return number||boolean ----@diagnostic disable-next-line: duplicate-set-field +---@return number|boolean Phone.GetPlayerPhone = function(src) return exports['qs-base']:GetPlayerPhone(src) or false end ----comment +---This will send an email to the passed source, email address, title and message. ---@param src number ---@param email string ---@param title string diff --git a/modules/progressbar/ox_lib/client.lua b/modules/progressbar/ox_lib/client.lua index c7bdb21..60bb24d 100644 --- a/modules/progressbar/ox_lib/client.lua +++ b/modules/progressbar/ox_lib/client.lua @@ -1,9 +1,13 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "ox_lib" local configValue = BridgeClientConfig.ProgressBarSystem if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ProgressBar = ProgressBar or {} +---This function converts a QB progress bar options table to an Ox progress bar options table. +---@param options table +---@return table local function convertFromQB(options) if not options then return options end local prop1 = options.prop or {} @@ -13,7 +17,7 @@ local function convertFromQB(options) model = prop1.model, bone = prop1.bone, pos = prop1.coords, - rot = prop1.rotation, + rot = prop1.rotation, }, { model = prop2.model, @@ -22,8 +26,6 @@ local function convertFromQB(options) rot = prop2.rotation, } } - - return { duration = options.duration, label = options.label, @@ -38,18 +40,18 @@ local function convertFromQB(options) }, anim = { dict = options.animation?.animDict, - clip = options.animation?.anim + clip = options.animation?.anim, + flag = options.animation?.flags or 49, }, prop = props, } end ----comment +---This function opens a progress bar. ---@param options table ---@param cb any ----@param isQBInput boolean ----@return nil ----@diagnostic disable-next-line: duplicate-set-field +---@param isQBInput boolean||optional +---@return boolean function ProgressBar.Open(options, cb, isQBInput) if isQBInput then options = convertFromQB(options) @@ -62,23 +64,4 @@ function ProgressBar.Open(options, cb, isQBInput) return success end -return ProgressBar - ---[[ -RegisterCommand("progressbar", function() - ProgressBar.Open({ - duration = 5000, - label = "Searching", - disable = { - move = true, - combat = true - }, - anim = { - dict = "anim@amb@clubhouse@tutorial@bkr_tut_ig3@", - clip = "machinic_loop_mechandplayer" - } - }, function(cancelled) - print(cancelled and "Cancelled" or "Complete") - end) -end) ---]] +return ProgressBar \ No newline at end of file diff --git a/modules/progressbar/qb-progressbar/client.lua b/modules/progressbar/qb-progressbar/client.lua index 4908ff1..11fb7e4 100644 --- a/modules/progressbar/qb-progressbar/client.lua +++ b/modules/progressbar/qb-progressbar/client.lua @@ -1,9 +1,13 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "progressbar" local configValue = BridgeClientConfig.ProgressBarSystem if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ProgressBar = ProgressBar or {} +---This function converts an Ox progress bar options table to a QB progress bar options table. +---@param options table +---@return table local function convertFromOx(options) if not options then return options end local prop1 = options.prop?[1] or options.prop or {} @@ -23,29 +27,28 @@ local function convertFromOx(options) animation = { animDict = options.anim?.dict, anim = options.anim?.clip, - flags = 49 + flags = options.anim?.flag or 49 }, prop = { model = prop1.model, bone = prop1.bone, - coords = prop1.pos, + coords = prop1.pos, rotation = prop1.rot }, propTwo = { model = prop2.model, bone = prop2.bone, - coords = prop2.pos, + coords = prop2.pos, rotation = prop2.rot } } end ----comment +---This function opens a progress bar. ---@param options table ---@param cb any ---@param qbFormat boolean ----@return success boolean ----@diagnostic disable-next-line: duplicate-set-field +---@return boolean boolean function ProgressBar.Open(options, cb, qbFormat) if not exports['progressbar'] then return false end @@ -60,30 +63,4 @@ function ProgressBar.Open(options, cb, qbFormat) return Citizen.Await(prom) end -return ProgressBar - - --- Example usage: ---[[ -RegisterCommand("progressbar", function() - ProgressBar.Open({ - duration = 5000, - label = "Searching", - disable = { - move = true, - combat = true - }, - anim = { - dict = "anim@amb@clubhouse@tutorial@bkr_tut_ig3@", - clip = "machinic_loop_mechandplayer" - }, - prop = { - model = "prop_ar_arrow_3", - pos = vector3(0.0, 0.0, 0.0), - rot = vector3(0.0, 0.0, 0.0) - }, - }, function(cancelled) - print(cancelled and "Cancelled" or "Complete") - end) -end) ---]] +return ProgressBar \ No newline at end of file diff --git a/modules/shops/_default/server.lua b/modules/shops/_default/server.lua index a4ac7b4..dc5e7a3 100644 --- a/modules/shops/_default/server.lua +++ b/modules/shops/_default/server.lua @@ -2,7 +2,7 @@ Shops = Shops or {} local registeredShops = {} ----commentThis can open a shop for the client +---This can open a shop for the client ---@param src number ---@param shopTitle string ---@return boolean diff --git a/modules/skills/_default/client.lua b/modules/skills/_default/client.lua index 74f9d3e..d1b4b4e 100644 --- a/modules/skills/_default/client.lua +++ b/modules/skills/_default/client.lua @@ -1,17 +1,23 @@ +---@diagnostic disable: duplicate-set-field Skills = Skills or {} local function warnUser() print("Currently only a few skill systems are supported by Community Bridge, you are using a resource that requires the skills module to be used.") end ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Skills system being being used. +---@return string Skills.GetResourceName = function() return "none" end ----@diagnostic disable-next-line: duplicate-set-field +---This will get the skill level of the passed skill name. +---@param skillName string +---@return number +---@return nil Skills.GetSkillLevel = function(skillName) - return 0, warnUser() + warnUser() + return 0 end return Skills \ No newline at end of file diff --git a/modules/skills/_default/server.lua b/modules/skills/_default/server.lua index e1b2302..8d2f333 100644 --- a/modules/skills/_default/server.lua +++ b/modules/skills/_default/server.lua @@ -1,27 +1,43 @@ +---@diagnostic disable: duplicate-set-field Skills = Skills or {} local function warnUser() print("Currently only a few skill systems are supported by Community Bridge, you are using a resource that requires the skills module to be used.") end ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Skills system being being used. +---@return string Skills.GetResourceName = function() return "none" end ----@diagnostic disable-next-line: duplicate-set-field +---This will get the skill level of the passed skill name. +---@param src number +---@param skillName string +---@return number Skills.GetSkillLevel = function(src, skillName) - return 0, warnUser() + warnUser() + return 0 end ----@diagnostic disable-next-line: duplicate-set-field +---This will add xp to the passed skill name. +---@param src number +---@param skillName string +---@param amount number +---@return boolean Skills.AddXp = function(src, skillName, amount) - return false, warnUser() + warnUser() + return false end ----@diagnostic disable-next-line: duplicate-set-field +---This will remove xp from the passed skill name. +---@param src number +---@param skillName string +---@param amount number +---@return boolean Skills.RemoveXp = function(src, skillName, amount) - return false, warnUser() + warnUser() + return false end return Skills \ No newline at end of file diff --git a/modules/skills/evolent_skills/client.lua b/modules/skills/evolent_skills/client.lua index 745b5a8..b471888 100644 --- a/modules/skills/evolent_skills/client.lua +++ b/modules/skills/evolent_skills/client.lua @@ -1,14 +1,18 @@ +---@diagnostic disable: duplicate-set-field Skills = Skills or {} local resourceName = "evolent_skills" local configValue = BridgeSharedConfig.Skills if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Skills system being used. +---@return string Skills.GetResourceName = function() return resourceName end ----@diagnostic disable-next-line: duplicate-set-field +---This will return the skill level of the passed skill name. +---@param skillName string +---@return number Skills.GetSkillLevel = function(skillName) local skillData = exports.evolent_skills:getSkillLevel(skillName) return skillData or 0 diff --git a/modules/skills/evolent_skills/server.lua b/modules/skills/evolent_skills/server.lua index 935a184..56a4700 100644 --- a/modules/skills/evolent_skills/server.lua +++ b/modules/skills/evolent_skills/server.lua @@ -1,20 +1,30 @@ +---@diagnostic disable: duplicate-set-field + Skills = Skills or {} local resourceName = "evolent_skills" local configValue = BridgeSharedConfig.Skills if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Skills system being used. +---@return string Skills.GetResourceName = function() return resourceName end ----@diagnostic disable-next-line: duplicate-set-field +---This will return the skill level of the passed skill name. +---@param src number +---@param skillName string +---@return number Skills.GetSkillLevel = function(src, skillName) local skillData = exports.evolent_skills:getSkillLevel(src, skillName) return skillData or 0 end ----@diagnostic disable-next-line: duplicate-set-field +---This will add xp to the passed skill name. +---@param src number +---@param skillName string +---@param amount number +---@return boolean Skills.AddXp = function(src, skillName, amount) local skillData = exports.evolent_skills:getSkillLevel(src, skillName) if not skillData then return false, print("Skill not found") end @@ -22,7 +32,11 @@ Skills.AddXp = function(src, skillName, amount) return true end ----@diagnostic disable-next-line: duplicate-set-field +---This will remove xp from the passed skill name. +---@param src number +---@param skillName string +---@param amount number +---@return boolean Skills.RemoveXp = function(src, skillName, amount) local skillData = exports.evolent_skills:getSkillLevel(src, skillName) if not skillData then return false, print("Skill not found") end diff --git a/modules/skills/OT_skills/client.lua b/modules/skills/ot_skills/client.lua similarity index 66% rename from modules/skills/OT_skills/client.lua rename to modules/skills/ot_skills/client.lua index 4d0e9f1..d619467 100644 --- a/modules/skills/OT_skills/client.lua +++ b/modules/skills/ot_skills/client.lua @@ -1,14 +1,19 @@ +---@diagnostic disable: duplicate-set-field + Skills = Skills or {} local resourceName = "OT_skills" local configValue = BridgeSharedConfig.Skills if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field +---This will return the name of the Skills system being used. +---@return string Skills.GetResourceName = function() return resourceName end ----@diagnostic disable-next-line: duplicate-set-field +---This will return the skill level of the passed skill name. +---@param skillName string +---@return number Skills.GetSkillLevel = function(skillName) local skillData = exports.OT_skills:getSkill(skillName) return skillData.level or 0 diff --git a/modules/skills/OT_skills/server.lua b/modules/skills/ot_skills/server.lua similarity index 65% rename from modules/skills/OT_skills/server.lua rename to modules/skills/ot_skills/server.lua index 7685012..ba0c39b 100644 --- a/modules/skills/OT_skills/server.lua +++ b/modules/skills/ot_skills/server.lua @@ -1,19 +1,30 @@ +---@diagnostic disable: duplicate-set-field + Skills = Skills or {} local resourceName = "OT_skills" local configValue = BridgeSharedConfig.Skills if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field +---This will return the name of the Skills system being used. +---@return string Skills.GetResourceName = function() return resourceName end ----@diagnostic disable-next-line: duplicate-set-field +---This will return the skill level of the passed skill name. +---@param src number +---@param skillName string +---@return number Skills.GetSkillLevel = function(src, skillName) local skillData = exports.OT_skills:getSkill(src, skillName) return skillData.level or 0 end +---This will add xp to the passed skill name. +---@param src number +---@param skillName string +---@param amount number +---@return boolean Skills.AddXp = function(src, skillName, amount) local skillData = exports.OT_skills:getSkill(src, skillName) if not skillData then return false, print("Skill not found") end @@ -21,6 +32,11 @@ Skills.AddXp = function(src, skillName, amount) return true end +---This will remove xp from the passed skill name. +---@param src number +---@param skillName string +---@param amount number +---@return boolean Skills.RemoveXp = function(src, skillName, amount) local skillData = exports.OT_skills:getSkill(src, skillName) if not skillData then return false, print("Skill not found") end diff --git a/modules/skills/pickle_xp/client.lua b/modules/skills/pickle_xp/client.lua index 4692acc..89bd99b 100644 --- a/modules/skills/pickle_xp/client.lua +++ b/modules/skills/pickle_xp/client.lua @@ -1,16 +1,20 @@ +---@diagnostic disable: duplicate-set-field Skills = Skills or {} local resourceName = "pickle_xp" local configValue = BridgeSharedConfig.Skills if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Skills system being used. +---@return string Skills.GetResourceName = function() return resourceName end ----@diagnostic disable-next-line: duplicate-set-field +---This will return the skill level of the passed skill name. +---@param skillName string +---@return number Skills.GetSkillLevel = function(skillName) - local skillData = exports.OT_skills:GetLevel(skillName) + local skillData = exports.pickle_xp:GetLevel(skillName) return skillData or 0 end diff --git a/modules/skills/pickle_xp/server.lua b/modules/skills/pickle_xp/server.lua index 82ef781..4a00ae0 100644 --- a/modules/skills/pickle_xp/server.lua +++ b/modules/skills/pickle_xp/server.lua @@ -1,19 +1,30 @@ +---@diagnostic disable: duplicate-set-field + Skills = Skills or {} local resourceName = "pickle_xp" local configValue = BridgeSharedConfig.Skills if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end ----@diagnostic disable-next-line: duplicate-set-field +---This will get the name of the Skills system being used. +---@return string Skills.GetResourceName = function() return resourceName end ----@diagnostic disable-next-line: duplicate-set-field +---This will return the skill level of the passed skill name. +---@param src number +---@param skillName string +---@return number Skills.GetSkillLevel = function(src, skillName) local skillData = exports.pickle_xp:GetPlayerLevel(src, skillName) return skillData or 0 end +---This will add xp to the passed skill name. +---@param src number +---@param skillName string +---@param amount number +---@return boolean Skills.AddXp = function(src, skillName, amount) local skillData = exports.pickle_xp:GetPlayerLevel(src, skillName) if not skillData then return false, print("Skill not found") end @@ -21,6 +32,11 @@ Skills.AddXp = function(src, skillName, amount) return true end +---This will remove xp from the passed skill name. +---@param src number +---@param skillName string +---@param amount number +---@return boolean Skills.RemoveXp = function(src, skillName, amount) local skillData = exports.pickle_xp:GetPlayerLevel(src, skillName) if not skillData then return false, print("Skill not found") end diff --git a/modules/target/_default/client.lua b/modules/target/_default/client.lua index 37581d7..25a3478 100644 --- a/modules/target/_default/client.lua +++ b/modules/target/_default/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field Target = Target or {} local function warnUser() diff --git a/modules/target/_default/init.lua b/modules/target/_default/init.lua new file mode 100644 index 0000000..d7a1e3f --- /dev/null +++ b/modules/target/_default/init.lua @@ -0,0 +1,16 @@ +-- local Target = Require('modules/target/_default/init.lua') +local requiredModules = { + 'modules/target/_default/client.lua', + 'modules/target/qb-target/client.lua', + 'modules/target/ox_target/client.lua' +} + +local Module = nil +for _, path in pairs(requiredModules) do + local module = Require(path) + if module then + Module = module + end +end + +return Module or error('No target module found. Please ensure you have one of the required target modules installed: ' .. table.concat(requiredModules, ', ')) \ No newline at end of file diff --git a/modules/target/ox_target/client.lua b/modules/target/ox_target/client.lua index d65b7e6..b5b7d17 100644 --- a/modules/target/ox_target/client.lua +++ b/modules/target/ox_target/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "ox_target" -local configValue = BridgeClientConfig.TargetSystem -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end local targetDebug = false local function detectDebugEnabled() @@ -30,6 +29,7 @@ Target.FixOptions = function(options) return action(entityOrData) end options[k].onSelect = select + options[k].groups = v.job or v.groups end return options end @@ -60,7 +60,7 @@ Target.AddGlobalVehicle = function(options) ox_target:addGlobalVehicle(options) end ----This will remove target options from all vehicles. +---This will remove target options from all vehicles. ---@param options table Target.RemoveGlobalVehicle = function(options) local assembledLables = {} @@ -80,8 +80,9 @@ end ---This will remove the target options from a local entity. This is useful for when you want to remove target options from a specific entity. ---@param entity any -Target.RemoveLocalEntity = function(entity) - ox_target:removeLocalEntity(entity) +---@param labels string | table | nil +Target.RemoveLocalEntity = function(entities, optionNames) + ox_target:removeLocalEntity(entities, optionNames) end ---This will add target options to all specified models. This is useful for when you want to add target options to all models of a specific type. @@ -98,25 +99,51 @@ Target.RemoveModel = function(model) ox_target:removeModel(model) end +-- Target.DisableTargeting = function(bool) +-- ox_target:disableTargeting(bool) +-- end + +-- Target.Refresh = function() +-- ox_target:disableTargeting(true) +-- Wait(10) +-- ox_target:disableTargeting(false) +-- end + + + ---This will add a box zone to the target system. This is useful for when you want to add target options to a specific area. ---@param name string ---@param coords table ---@param size table ---@param heading number ---@param options table -Target.AddBoxZone = function(name, coords, size, heading, options) - options = Target.FixOptions(options) +Target.AddBoxZone = function(name, coords, size, heading, options, debug) + options = Target.FixOptions(options or {}) + if not next(options) then return end local target = ox_target:addBoxZone({ coords = coords, size = size, rotation = heading, - debug = targetDebug, + debug = debug or targetDebug, options = options, }) table.insert(targetZones, { name = name, id = target, creator = GetInvokingResource() }) return target end +-- RegisterCommand('boxzone:test', function(source, args, rawCommand) +-- local coords = GetEntityCoords(PlayerPedId()) +-- Target.AddBoxZone('test_zone', coords, { 2.0, 2.0, 2.0 }, 0.0, { +-- { +-- label = 'Test Option', +-- icon = 'fas fa-check', +-- onSelect = function() +-- print('Test option selected!') +-- end +-- } +-- }, true) +-- end) + ---This will add a circle zone to the target system. This is useful for when you want to add target options to a specific area. ---@param name string ---@param coords table diff --git a/modules/target/qb-target/client.lua b/modules/target/qb-target/client.lua index 516b4e8..79a6163 100644 --- a/modules/target/qb-target/client.lua +++ b/modules/target/qb-target/client.lua @@ -1,7 +1,7 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "qb-target" -local configValue = BridgeClientConfig.TargetSystem -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end -if GetResourceState('ox_target') == 'started' then return end -- this is for older versions of ox that supported the backwards compatability. As its depricated we dont want to touch that. +if GetResourceState(resourceName) == 'missing' then return end +if GetResourceState("ox_target") == 'started' then return end local targetDebug = false local function detectDebugEnabled() @@ -67,7 +67,7 @@ Target.AddGlobalVehicle = function(options) }) end ----This will remove target options from all vehicles. +---This will remove target options from all vehicles. ---@param options table Target.RemoveGlobalVehicle = function(options) local assembledLables = {} @@ -89,9 +89,10 @@ Target.AddLocalEntity = function(entities, options) end ---This will remove the target options from a local entity. This is useful for when you want to remove target options from a specific entity. ----@param entity any -Target.RemoveLocalEntity = function(entity) - qb_target:RemoveTargetEntity(entity) +---@param entity number | table +---@param labels string | table | nil +Target.RemoveLocalEntity = function(entity, labels) + qb_target:RemoveTargetEntity(entity, labels) end ---This will add target options to all specified models. This is useful for when you want to add target options to all models of a specific type. @@ -111,20 +112,32 @@ Target.RemoveModel = function(model) qb_target:RemoveTargetModel(model) end +-- Target.DisableTargeting = function(bool) +-- qb_target:AllowTargeting(bool) +-- end + +-- Target.Refresh = function() +-- qb_target:AllowTargeting(false) +-- Wait(10) +-- qb_target:AllowTargeting(true) +-- end + + ---This will add a box zone to the target system. This is useful for when you want to add target options to a specific area. ---@param name string ---@param coords table ---@param size table ---@param heading number ---@param options table -Target.AddBoxZone = function(name, coords, size, heading, options) +Target.AddBoxZone = function(name, coords, size, heading, options, debug) options = Target.FixOptions(options) + if not next(options) then return end qb_target:AddBoxZone(name, coords, size.x, size.y, { name = name, - debugPoly = targetDebug, + debugPoly = debug or targetDebug, heading = heading, - minZ = coords.z - (size.x * 0.5), - maxZ = coords.z + (size.x * 0.5), + minZ = coords.z - (size.z * 0.5), + maxZ = coords.z + (size.z * 0.5), }, { options = options, distance = options.distance or 1.5, diff --git a/modules/target/sleepless_interact/client.lua b/modules/target/sleepless_interact/client.lua index 0e924b2..b6011a7 100644 --- a/modules/target/sleepless_interact/client.lua +++ b/modules/target/sleepless_interact/client.lua @@ -1,7 +1,7 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "sleepless_interact" -local configValue = BridgeClientConfig.TargetSystem -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end +if GetResourceState("ox_target") == 'started' then return end local targetDebug = false local function detectDebugEnabled() @@ -40,7 +40,6 @@ Target.AddGlobalPlayer = function(options) end Target.DisableTargeting = function(bool) - --sleepless_interact:disableTargeting(bool) sleepless_interact:disableInteract(bool) end @@ -104,9 +103,10 @@ end ---comment ---@param entity number +---@param labels string | table | nil ---@return nil -Target.RemoveLocalEntity = function(entity) - sleepless_interact:removeLocalEntity(entity) +Target.RemoveLocalEntity = function(entity, labels) + sleepless_interact:removeLocalEntity(entity, labels) end ---comment @@ -129,6 +129,17 @@ Target.RemoveZone = function(name) end end +-- Target.DisableTargeting = function(bool) +-- sleepless_interact:disableInteract(bool) +-- end + +-- Target.Refresh = function() +-- sleepless_interact:disableInteract(false) +-- Wait(10) +-- sleepless_interact:disableInteract(true) +-- end + + AddEventHandler('onResourceStop', function(resource) if resource == GetCurrentResourceName() then for _, target in pairs(targetZones) do diff --git a/modules/vehicleKey/F_RealCarKeysSystem/client/client.lua b/modules/vehicleKey/F_RealCarKeysSystem/client/client.lua index 5ba0f96..249c770 100644 --- a/modules/vehicleKey/F_RealCarKeysSystem/client/client.lua +++ b/modules/vehicleKey/F_RealCarKeysSystem/client/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "F_RealCarKeysSystem" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} VehicleKey.GiveKeys = function(vehicle, plate) diff --git a/modules/vehicleKey/MrNewbVehicleKeys/client/client.lua b/modules/vehicleKey/MrNewbVehicleKeys/client/client.lua index 2790419..a05405f 100644 --- a/modules/vehicleKey/MrNewbVehicleKeys/client/client.lua +++ b/modules/vehicleKey/MrNewbVehicleKeys/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "MrNewbVehicleKeys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/Renewed-Vehiclekeys/client/client.lua b/modules/vehicleKey/Renewed-Vehiclekeys/client/client.lua index baf44c4..62e4da7 100644 --- a/modules/vehicleKey/Renewed-Vehiclekeys/client/client.lua +++ b/modules/vehicleKey/Renewed-Vehiclekeys/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "Renewed-Vehiclekeys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/_default/client/client.lua b/modules/vehicleKey/_default/client/client.lua index 283a143..adb02d3 100644 --- a/modules/vehicleKey/_default/client/client.lua +++ b/modules/vehicleKey/_default/client/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field VehicleKey = VehicleKey or {} ---This will give keys to the specifed vehicle/plate. diff --git a/modules/vehicleKey/cd_garage/client/client.lua b/modules/vehicleKey/cd_garage/client/client.lua index 7250703..9ab85d1 100644 --- a/modules/vehicleKey/cd_garage/client/client.lua +++ b/modules/vehicleKey/cd_garage/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "cd_garage" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/jacksam/client.lua b/modules/vehicleKey/jacksam/client.lua index 4259aa4..0da5d3e 100644 --- a/modules/vehicleKey/jacksam/client.lua +++ b/modules/vehicleKey/jacksam/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "jaksams_VehiclesKeys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/mk_vehiclekeys/client/client.lua b/modules/vehicleKey/mk_vehiclekeys/client/client.lua index 58227de..0c7d643 100644 --- a/modules/vehicleKey/mk_vehiclekeys/client/client.lua +++ b/modules/vehicleKey/mk_vehiclekeys/client/client.lua @@ -1,7 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "mk_vehiclekeys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end - +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} VehicleKey.GiveKeys = function(vehicle, plate) diff --git a/modules/vehicleKey/mono_carkeys/client/client.lua b/modules/vehicleKey/mono_carkeys/client/client.lua index 793bd5a..7ee881a 100644 --- a/modules/vehicleKey/mono_carkeys/client/client.lua +++ b/modules/vehicleKey/mono_carkeys/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "mono_carkeys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} VehicleKey.GiveKeys = function(vehicle, plate) diff --git a/modules/vehicleKey/okokGarage/client/client.lua b/modules/vehicleKey/okokGarage/client/client.lua index 27dba9a..705c2f0 100644 --- a/modules/vehicleKey/okokGarage/client/client.lua +++ b/modules/vehicleKey/okokGarage/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "okokGarage" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/qb-vehiclekeys/client/client.lua b/modules/vehicleKey/qb-vehiclekeys/client/client.lua index f553cea..861c8d8 100644 --- a/modules/vehicleKey/qb-vehiclekeys/client/client.lua +++ b/modules/vehicleKey/qb-vehiclekeys/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "qb-vehiclekeys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/qbx_vehiclekeys/client/client.lua b/modules/vehicleKey/qbx_vehiclekeys/client/client.lua index a815939..0502ac1 100644 --- a/modules/vehicleKey/qbx_vehiclekeys/client/client.lua +++ b/modules/vehicleKey/qbx_vehiclekeys/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "qbx_vehiclekeys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/qs-vehiclekeys/client/client.lua b/modules/vehicleKey/qs-vehiclekeys/client/client.lua index 6f8c3e0..2280713 100644 --- a/modules/vehicleKey/qs-vehiclekeys/client/client.lua +++ b/modules/vehicleKey/qs-vehiclekeys/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "qs-vehiclekeys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/t1ger_keys/client/client.lua b/modules/vehicleKey/t1ger_keys/client/client.lua index e2107b4..a040a7a 100644 --- a/modules/vehicleKey/t1ger_keys/client/client.lua +++ b/modules/vehicleKey/t1ger_keys/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "t1ger_keys" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/vehicleKey/wasabi_carlock/client/client.lua b/modules/vehicleKey/wasabi_carlock/client/client.lua index a66377a..bde20f5 100644 --- a/modules/vehicleKey/wasabi_carlock/client/client.lua +++ b/modules/vehicleKey/wasabi_carlock/client/client.lua @@ -1,6 +1,6 @@ +---@diagnostic disable: duplicate-set-field local resourceName = "wasabi_carlock" -local configValue = BridgeClientConfig.VehicleKey -if (configValue == "auto" and GetResourceState(resourceName) ~= "started") or (configValue ~= "auto" and configValue ~= resourceName) then return end +if GetResourceState(resourceName) == 'missing' then return end VehicleKey = VehicleKey or {} diff --git a/modules/weather/_default/client.lua b/modules/weather/_default/client.lua index 095bf46..7625ab6 100644 --- a/modules/weather/_default/client.lua +++ b/modules/weather/_default/client.lua @@ -1,3 +1,4 @@ +---@diagnostic disable: duplicate-set-field Weather = Weather or {} ---This will toggle the players weather/time sync diff --git a/modules/weather/cd_easytime/client.lua b/modules/weather/cd_easytime/client.lua index 7808160..210ca56 100644 --- a/modules/weather/cd_easytime/client.lua +++ b/modules/weather/cd_easytime/client.lua @@ -1,8 +1,10 @@ -if GetResourceState('cd_easytime') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('cd_easytime') == 'missing' then return end Weather = Weather or {} ----comment +---This will toggle the players weather/time sync ---@param toggle boolean +---@return nil Weather.ToggleSync = function(toggle) TriggerEvent('cd_easytime:PauseSync', toggle) end diff --git a/modules/weather/qb-weathersync/client/client.lua b/modules/weather/qb-weathersync/client/client.lua index df628c7..548bc23 100644 --- a/modules/weather/qb-weathersync/client/client.lua +++ b/modules/weather/qb-weathersync/client/client.lua @@ -1,8 +1,10 @@ -if GetResourceState('qb-weathersync') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('qb-weathersync') == 'missing' then return end Weather = Weather or {} ----comment +---This will toggle the players weather/time sync ---@param toggle boolean +---@return nil Weather.ToggleSync = function(toggle) if toggle then TriggerEvent("qb-weathersync:client:EnableSync") diff --git a/modules/weather/renewed-weathersync/client/client.lua b/modules/weather/renewed-weathersync/client/client.lua index d531bee..9d4d460 100644 --- a/modules/weather/renewed-weathersync/client/client.lua +++ b/modules/weather/renewed-weathersync/client/client.lua @@ -1,8 +1,10 @@ -if GetResourceState('Renewed-Weathersync') ~= 'started' then return end +---@diagnostic disable: duplicate-set-field +if GetResourceState('Renewed-Weathersync') == 'missing' then return end Weather = Weather or {} ----comment +---This will toggle the players weather/time sync ---@param toggle boolean +---@return nil Weather.ToggleSync = function(toggle) LocalPlayer.state.syncWeather = toggle end diff --git a/settings/clientConfig.lua b/settings/clientConfig.lua index 6da8aee..4de534d 100644 --- a/settings/clientConfig.lua +++ b/settings/clientConfig.lua @@ -2,11 +2,8 @@ BridgeClientConfig = {} BridgeClientConfig.InputSystem = "auto" -- [ auto | ox_lib | qb-input ] BridgeClientConfig.MenuSystem = "auto" -- [ auto | ox_lib | qb-menu ] BridgeClientConfig.ProgressBarSystem = "auto" -- [ auto | ox_lib | progressbar ] -BridgeClientConfig.VehicleKey = -"auto" -- [ auto | qb-vehiclekeys | MrNewbVehicleKeys | jaksams_VehiclesKeys | wasabi_carlock | mk_vehiclekeys | qbx_vehiclekeys | qs-vehiclekeys | t1ger_keys | Renewed-Vehiclekeys | mono_carkeys| cd_garage | okokGarage | F_RealCarKeysSystem -BridgeClientConfig.Fuel = -"auto" -- [ auto | LegacyFuel | ox_fuel | ps-fuel | qs-fuelstations | Renewed-Fuel | ti_fuel | lc_fuel | x-fuel | cdn-fuel | esx-sna-fuel | BigDaddy-Fuel | okokGasStation ] -BridgeClientConfig.TargetSystem = -"auto" -- [ auto | ox_target | qb-target | sleepless_interact ] -- sleepless is only partially supported and would need another system in place +BridgeClientConfig.VehicleKey = "auto" -- [ auto | qb-vehiclekeys | MrNewbVehicleKeys | jaksams_VehiclesKeys | wasabi_carlock | mk_vehiclekeys | qbx_vehiclekeys | qs-vehiclekeys | t1ger_keys | Renewed-Vehiclekeys | mono_carkeys| cd_garage | okokGarage | F_RealCarKeysSystem +BridgeClientConfig.Fuel = "auto" -- [ auto | LegacyFuel | ox_fuel | ps-fuel | qs-fuelstations | Renewed-Fuel | ti_fuel | lc_fuel | x-fuel | cdn-fuel | esx-sna-fuel | BigDaddy-Fuel | okokGasStation ] +BridgeClientConfig.TargetSystem = "auto" -- [ auto | ox_target | qb-target | sleepless_interact ] -- sleepless is only partially supported and would need another system in place BridgeClientConfig.Debug = false return BridgeClientConfig diff --git a/unit_tests/callbacks_test.lua b/unit_tests/callbacks_test.lua index 55247cf..ada0ea7 100644 --- a/unit_tests/callbacks_test.lua +++ b/unit_tests/callbacks_test.lua @@ -7,7 +7,7 @@ -- -- -- -- -- -- -- -- -- -- if not IsDuplicityVersion() then goto client end -exports.community_bridge:RegisterCallback('callback_test1_name_here', function(src, var1) +Bridge.Callbacks.Register('callback_test1_name_here', function(src, var1) if var1 == "herpaderpa" then print("this is a test") end @@ -15,7 +15,7 @@ exports.community_bridge:RegisterCallback('callback_test1_name_here', function(s end) RegisterCommand('callback_test2', function(source) - local someData, other = exports.community_bridge:TriggerCallback('callback_test2_name_here', source, "herpaderpa") + local someData, other = Bridge.Callbacks.Trigger('callback_test2_name_here', source, "herpaderpa") print("Data From Client: ", someData, other) end) @@ -27,7 +27,7 @@ if IsDuplicityVersion() then return end ::client:: RegisterCommand('callback_test1', function() - local somerandomstring, someotherrandomstring = exports.community_bridge:TriggerCallback('callback_test1_name_here', "herpaderpa") + local somerandomstring, someotherrandomstring = Bridge.Callbacks.Trigger('callback_test1_name_here', "herpaderpa") print("Data From Server: ", somerandomstring, someotherrandomstring) end) @@ -35,6 +35,6 @@ end) -- print("this is a rebound to all players") -- end) -exports.community_bridge:RegisterCallback('callback_test2_name_here', function(ftpcsftug) +Bridge.Callbacks.Register('callback_test2_name_here', function(ftpcsftug) return ftpcsftug, 'TestyMcTesterton' end) diff --git a/unit_tests/input_test.lua b/unit_tests/input_test.lua new file mode 100644 index 0000000..9e2635c --- /dev/null +++ b/unit_tests/input_test.lua @@ -0,0 +1,234 @@ +-- Test QB Format Input +RegisterCommand('input_test_qb', function() + local qbFormatData = { + inputs = { + { + text = "Player Name", + name = "playername", + type = "text", + isRequired = true, + default = "John Doe" + }, + { + text = "Player ID", + name = "playerid", + type = "number", + isRequired = true + }, + { + text = "Password", + name = "password", + type = "password", + isRequired = false + }, + { + text = "Vehicle Type", + name = "vehicle", + type = "select", + isRequired = true, + options = { + {value = "car", text = "Car"}, + {value = "bike", text = "Motorcycle"}, + {value = "truck", text = "Truck"} + } + }, + { + text = "Enable Notifications", + name = "notifications", + type = "checkbox", + isRequired = false, + options = { + {value = "email", text = "Email", checked = true}, + {value = "sms", text = "SMS", checked = false} + } + } + } + } + + local result = Input.Open("QB Format Test", qbFormatData, true, "Submit") + if result then + print("QB Format Result:") + for k, v in pairs(result) do + print(k .. ": " .. tostring(v)) + end + else + print("QB Format: User cancelled or no input") + end +end, false) + +-- Test Ox Format Input +RegisterCommand('input_test_ox', function() + local oxFormatData = { + { + type = "input", + label = "Character Name", + name = "charname", + required = true, + default = "Jane Smith" + }, + { + type = "number", + label = "Age", + name = "age", + required = true, + min = 18, + max = 100 + }, + { + type = "select", + label = "Job Category", + name = "jobcat", + required = true, + options = { + {value = "civ", label = "Civilian"}, + {value = "leo", label = "Law Enforcement"}, + {value = "ems", label = "Emergency Medical"} + } + }, + { + type = "checkbox", + label = "Has License", + name = "license", + required = false + }, + { + type = "color", + label = "Favorite Color", + name = "color", + default = "#ff0000" + }, + { + type = "date", + label = "Birth Date", + name = "birthdate", + format = "DD/MM/YYYY" + } + } + + local result = Input.Open("Ox Format Test", oxFormatData, false) + if result then + print("Ox Format Result:") + for k, v in pairs(result) do + print(k .. ": " .. tostring(v)) + end + else + print("Ox Format: User cancelled or no input") + end +end, false) + +-- Test Simple Text Input +RegisterCommand('input_test_simple', function() + local simpleData = { + inputs = { + { + text = "Enter your message", + name = "message", + type = "text", + isRequired = true + } + } + } + + local result = Input.Open("Simple Input", simpleData, true, "Send") + if result then + print("Simple Input Result: " .. (result.message or "No message")) + else + print("Simple Input: Cancelled") + end +end, false) + +-- Test All Input Types (QB Format) +RegisterCommand('input_test_all_types', function() + local allTypesData = { + inputs = { + { + text = "Text Input", + name = "text_field", + type = "text", + isRequired = false, + default = "Sample text" + }, + { + text = "Number Input", + name = "number_field", + type = "number", + isRequired = false, + default = 42 + }, + { + text = "Password Input", + name = "password_field", + type = "password", + isRequired = false + }, + { + text = "Radio Selection", + name = "radio_field", + type = "radio", + isRequired = false, + options = { + {value = "option1", text = "Option 1"}, + {value = "option2", text = "Option 2"}, + {value = "option3", text = "Option 3"} + } + }, + { + text = "Checkbox Options", + name = "checkbox_field", + type = "checkbox", + isRequired = false, + options = { + {value = "check1", text = "Check 1", checked = true}, + {value = "check2", text = "Check 2", checked = false}, + {value = "check3", text = "Check 3", checked = false} + } + }, + { + text = "Select Dropdown", + name = "select_field", + type = "select", + isRequired = false, + options = { + {value = "val1", text = "Value 1"}, + {value = "val2", text = "Value 2"}, + {value = "val3", text = "Value 3"} + } + } + } + } + + local result = Input.Open("All Input Types Test", allTypesData, true, "Test Submit") + if result then + print("All Types Result:", json.encode(result)) + + else + print("All Types: User cancelled") + end +end, false) + +-- Test Error Handling +RegisterCommand('input_test_error', function() + -- Test with invalid data + local result = Input.Open("Error Test", nil, true) + if result then + print("Error test unexpectedly succeeded") + else + print("Error test correctly handled nil data") + end + + -- Test with empty inputs + local emptyData = {inputs = {}} + local result2 = Input.Open("Empty Test", emptyData, true) + if result2 then + print("Empty test result: " .. json.encode(result2)) + else + print("Empty test: No result") + end +end, false) + +-- print("Input unit tests loaded. Available commands:") +-- print(" /input_test_qb - Test QB format input") +-- print(" /input_test_ox - Test Ox format input") +-- print(" /input_test_simple - Test simple text input") +-- print(" /input_test_all_types - Test all input types") +-- print(" /input_test_error - Test error handling") \ No newline at end of file diff --git a/unit_tests/locale_test.lua b/unit_tests/locale_test.lua index 3b55377..bd046bc 100644 --- a/unit_tests/locale_test.lua +++ b/unit_tests/locale_test.lua @@ -4,16 +4,13 @@ -- Instead of using Require you can also import it via the manifest. -- The Lang variable is available globally, which tells you what the server is using. -- print("Language: ", Lang) --- print("Locale: ", Language.Locale("locale-unit-test")) +-- print("Locale: ", Language.Locale("UNITTEST.locale-unit-test")) -- Example outside community bridge resource: -- local Language = Require('modules/locales/shared.lua') -- print("Language: ", Lang) --- print("Locale: ", Language.Locale("locale-unit-test")) +-- print("Locale: ", Language.Locale("UNITTEST.locale-unit-test")) RegisterCommand("lang", function(source, args, raw) - print(Language.Locale("UNITTEST.UNITTEST.UNITTESTA")) - print(Language.Locale("UNITTEST.UNITTESTA", "Devil", "GERRRRRRR!")) - - print( "Oh also this works", Language.Locale("place_object_scroll_down")) + print( "Oh also this works", Language.Locale("placeable_object.place_object_scroll_down")) end, false) \ No newline at end of file diff --git a/unit_tests/placeable_object.lua b/unit_tests/placeable_object.lua new file mode 100644 index 0000000..4ad9b81 --- /dev/null +++ b/unit_tests/placeable_object.lua @@ -0,0 +1,29 @@ +local isPlacing = false +RegisterCommand('startplacer', function(source, args, rawCommand) + if Bridge.PlaceableObject.IsPlacing() then + print("Already placing an object.") + return + end + + local model = args[1] or 'prop_barrel_01a' -- Default model if none provided + local position = GetEntityCoords(PlayerPedId()) + local result = Bridge.PlaceableObject.Create(model, { + allowMovement = true, -- Enable movement mode + allowNormal = true, -- Enable normal mode + allowVertical = false, -- Allow vertical movement in normal mode + startMode = 'normal', -- Start in normal mode + depthMin = 2.0, + depthMax = 15.0, + heightStep = 0.2, -- Height adjustment step + boundary = {min = vector3(position.x - 5, position.y - 5, position.z - 1.5), max = vector3(position.x + 5, position.y + 5, position.z + 10)}, + showInstructionalButtons = true, -- Show instructional buttons + }) + + if result then + print("Object placed!") + print("Position:", result.position) + print("Heading:", result.heading) + else + print("Placement cancelled") + end +end) \ No newline at end of file diff --git a/web/dist/index.html b/web/dist/index.html index 3a310af..b6a3bd9 100644 --- a/web/dist/index.html +++ b/web/dist/index.html @@ -10,4 +10,41 @@
+ diff --git a/web/index.html b/web/index.html index e5c7529..d427a2b 100644 --- a/web/index.html +++ b/web/index.html @@ -9,4 +9,39 @@
+