Merge pull request #114 from The-Order-Of-The-Sacred-Framework/dev

Dev
This commit is contained in:
MrNewb authored and GitHub committed 2025-06-09 00:36:38 -04:00
commit 698e59d811
217 files changed
+6863 -2434

No files matched your search

+39
View File
@@ -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
<!-- Please include a summary of the changes and the purpose of this PR -->
## Related Issues
<!-- If this PR addresses any issues, please link them here using "Fixes #issue_number" -->
## Testing Steps
<!-- Describe how the changes were tested and how reviewers can verify them -->
## Additional Notes
<!-- Add any other relevant information or context here -->
+115 -27
View File
@@ -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)
<details>
<summary>📝 Implementation Details</summary>
**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
</details>
---
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)
<details>
<summary>📝 Implementation Details</summary>
**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
</details>
---
### 📦 ox_lib
**Purpose:** External compatibility and architectural inspiration
**Repository:** [ox_lib](https://github.com/overextended/ox_lib)
<details>
<summary>📝 Implementation Details</summary>
**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
</details>
---
### 🏗️ renewed_lib
**Purpose:** Object placer functionality
**Repository:** [renewed_lib](https://github.com/Renewed-Scripts/Renewed-Lib)
<details>
<summary>📝 Implementation Details</summary>
**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
</details>
---
### 🔍 duff
**Purpose:** Version checker system and update notifications
**Repository:** [duff](https://github.com/DonHulieo/duff/blob/d89ed3b0051194babf5711114a0c437d4e41f433/server/init.lua#L10C1-L28C4)
<details>
<summary>📝 Implementation Details</summary>
**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
</details>
---
## 🌟 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
+317 -34
View File
@@ -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.
<div align="center">
![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**
</div>
---
## 🔧 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**
<details>
<summary>Click to expand core system compatibility</summary>
#### 📦 **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 |
</details>
### 🎨 **Developer Tools & Utilities**
<details>
<summary>Click to expand developer tools and utilities</summary>
#### 🛠️ **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
</details>
### 🎭 **Specialized Systems**
<details>
<summary>Click to expand specialized system integrations</summary>
#### 🏠 **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
</details>
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
<details>
<summary>Click to expand FAQ</summary>
**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.
</details>
---
## 🚀 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."
<div align="center">
**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)
</div>
---
## 🔍 SEO & Keywords
<details>
<summary>Click to expand SEO information and keywords</summary>
### 🏷️ 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`
</details>
-154
View File
@@ -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}
-38
View File
@@ -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
-103
View File
@@ -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})
+5 -3
View File
@@ -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',
}
+2 -3
View File
@@ -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
Bridge.RegisterModule("Dialogue", Dialogue)
+14 -20
View File
@@ -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
+83 -39
View File
@@ -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
+13 -17
View File
@@ -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
+3 -3
View File
@@ -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")
-154
View File
@@ -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
-347
View File
@@ -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
+5 -5
View File
@@ -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
+538 -152
View File
@@ -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
+2 -3
View File
@@ -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
+53
View File
@@ -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
+269
View File
@@ -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)
+379
View File
@@ -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 <shellId> <model>")
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)
+93 -48
View File
@@ -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<T|false, fun(): any> 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
View File
Whitespace-only changes.
+11
View File
@@ -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
+28
View File
@@ -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"
}
}
+28
View File
@@ -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] تدوير يسار"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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] Περιστροφή αριστερά"
}
}
+27 -44
View File
@@ -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"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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] बाईं ओर घुमाएं"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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] 左回転"
}
}
+28
View File
@@ -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] 왼쪽으로 회전"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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"
}
}
+27 -27
View File
@@ -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.",
}
}
"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"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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] Повернуть влево"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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] หมุนซ้าย"
}
}
+28
View File
@@ -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"
}
}
+28
View File
@@ -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": "[滚轮下] 向左转"
}
}
+28
View File
@@ -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": "[滾輪下] 向左轉"
}
}
+28
View File
@@ -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": "[滾輪下] 向左轉"
}
}
+28
View File
@@ -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": "[滚轮下] 向左转"
}
}
-212
View File
@@ -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
+149 -23
View File
@@ -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
+40 -16
View File
@@ -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
+7
View File
@@ -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
+212
View File
@@ -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)
+216
View File
@@ -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
@@ -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
@@ -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)
@@ -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?
@@ -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
@@ -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)
@@ -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?
+7
View File
@@ -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
+238
View File
@@ -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)
+201
View File
@@ -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
+66 -74
View File
@@ -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
@@ -1,3 +1,4 @@
---@diagnostic disable: duplicate-set-field
Dispatch = Dispatch or {}
---This will send an alert to currently supported dispatch systems.
+2 -2
View File
@@ -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
return Dispatch
@@ -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)
@@ -0,0 +1,4 @@
if GetResourceState('bub-mdt') == 'missing' then return end
Dispatch = Dispatch or {}
return Dispatch
@@ -1,4 +0,0 @@
if GetResourceState('bub-mdt') ~= 'started' then return end
Dispatch = Dispatch or {}
return Dispatch
@@ -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)
@@ -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
+3 -2
View File
@@ -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)
+1 -1
View File
@@ -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)
@@ -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)
@@ -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
@@ -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 {}
@@ -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 {}
@@ -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)
@@ -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
@@ -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)
@@ -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)
@@ -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)
@@ -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
+10
View File
@@ -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
+13
View File
@@ -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
+1 -1
View File
@@ -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 {}
+1 -1
View File
@@ -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 {}
+1 -1
View File
@@ -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 {}
+1 -1
View File
@@ -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 {}
+1 -1
View File
@@ -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 {}
+1 -1
View File
@@ -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 {}
+1 -1
View File
@@ -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 {}
+1 -1
View File
@@ -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 {}
+49 -15
View File
@@ -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()
+114 -30
View File
@@ -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)
+51 -4
View File
@@ -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')
+91 -24
View File
@@ -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)
Loaded 100 of 217 files, more files were not shown because too many files have changed in this diff. Show more