# CodeRanch - Zone System

**Advanced Safe Zone & Law Zone System for RedM**

This script provides a comprehensive zone management system for RedM servers. Create safe zones where weapons are prohibited, law zones with enforcement rules, and custom zones with special rules. Features an intuitive admin UI with old western design theme.

## 🚀 Features

* **Multi-Zone Types**: Safe zones, Law zones, and Custom zones
* **Automatic Weapon Detection**: Forces players to holster weapons in safe zones
* **PvP Protection**: Disables PvP and damage in safe zones
* **Visual Markers**: Draw markers on map showing zone boundaries
* **Admin Management UI**: Beautiful old western themed admin interface
* **Multi-Framework Support**: VORP, RedEM, RSG and Standalone
* **Discord Integration**: Log zone violations and admin actions
* **Punishment System**: Fine, jail, or auto-holster for law zone violations
* **3D Text Display**: Shows zone names and types above zones
* **Sound Effects**: Audio feedback on zone enter/exit
* **JSON Storage**: Zones saved to `zones.json` file
* **Zone Notifications**: Beautiful UI notifications when entering/exiting zones

## 📋 Requirements

* **RedM Server** (Beta 1491+)
* **Supported Frameworks**: VORP, RedEM, RSG or Standalone

## 🛠️ Installation

{% stepper %}
{% step %}

### Download Files

Copy the resource to your server's resources folder:

```bash
# Copy to your server's resources folder
resources/[coderanch]/coderanch-safezones/
```

{% endstep %}

{% step %}

### Server.cfg Settings

Add framework dependencies (only add the ones you use) and ensure the safe zones resource:

```cfg
# Framework dependencies (only add the ones you use)

# If using VORP
ensure vorp_core

# If using RedEM
ensure redem_roleplay

# If using RSG
ensure rsg-core

# Safe Zones Script
ensure coderanch-safezones
```

{% endstep %}

{% step %}

### Configuration

Edit `config.lua` file according to your server's needs.
{% endstep %}
{% endstepper %}

## ⚙️ Configuration

### Zone Check Settings

```lua
Config.CheckInterval = 2000  -- How often to check player position (milliseconds)
```

### Safe Zone Settings

```lua
Config.SafeZoneWeaponsDisabled = true   -- Auto-holster weapons in safe zones
Config.SafeZoneDisablePvP = true        -- Disable PvP in safe zones
Config.SafeZoneDisableDamage = true    -- Make players invincible in safe zones
```

### Law Zone Settings

```lua
Config.LawZoneWarningTime = 5      -- Warning time before punishment (seconds)
Config.LawZoneFineAmount = 10     -- Fine amount for violations
Config.LawZoneJailTime = 60       -- Jail time for violations (seconds)
Config.PunishmentMode = "fine"   -- Options: "fine", "jail", "auto_holster", "all"
```

### Admin Permissions

```lua
Config.AdminGroups = {"admin", "mod", "moderator"}
```

### Zone Drawing Settings

```lua
Config.DrawZones = true                    -- Enable zone markers
Config.DrawDistance = 150.0               -- Distance to show markers
Config.ZoneMarkerType = 28                -- Marker type (28 = Cylinder)
Config.ShowZoneText = true                -- Show 3D text above zones
Config.TextDisplayDistance = 100.0        -- Distance to show text

Config.ZoneDrawColor = {
    safe = {r = 0, g = 255, b = 0, a = 100},     -- Green for safe zones
    law = {r = 255, g = 165, b = 0, a = 100},   -- Orange for law zones
    custom = {r = 0, g = 150, b = 255, a = 100} -- Blue for custom zones
}
```

### Sound Settings

```lua
Config.PlaySounds = true  -- Enable sound effects on zone enter/exit
```

### Discord Integration

```lua
Config.DiscordWebhook = ""          -- Discord webhook URL (leave empty to disable)
Config.LogPunishments = true       -- Log violations to Discord
```

### Zone Messages

```lua
Config.Messages = {
    enterSafe = "You've entered %s - Holster your weapons",
    enterLaw = "You've entered %s - Law enforcement active",
    enterCustom = "You've entered %s",
    weaponWarning = "Warning: Holster your weapon or face consequences!",
    weaponHolstered = "Weapon holstered",
    fined = "You've been fined $%s for brandishing a weapon",
    jailed = "You've been jailed for %s seconds",
    noPermission = "You don't have permission to use this command",
    zoneCreated = "Zone '%s' created successfully",
    zoneDeleted = "Zone '%s' deleted successfully",
    zoneNotFound = "Zone not found",
    exitZone = "You've left %s"
}
```

### Default Zones

```lua
Config.DefaultZones = {
    {
        name = "Valentine",
        type = "law",
        coords = vector3(-278.4, 806.3, 119.3),
        radius = 150.0,
        blip = true
    },
    -- Add more default zones here
}
```

## 🎮 Usage

### For Admins

#### Creating a Zone

{% stepper %}
{% step %}

### Create via Command

Command: `/zone create [safe/law/custom]`\
Example: `/zone create safe` — Opens UI at your current position
{% endstep %}

{% step %}

### Create via UI

Command: `/zoneui` — Opens the admin management UI

In the UI:

* Click "Claim New Territory"
* Fill in zone details:
  * Territory Name: Name of the zone
  * Territory Classification: Safe, Law, or Custom
  * Territory Range: Radius in meters
  * Map Coordinates: X, Y, Z coordinates
* Click "Claim Territory"
  {% endstep %}
  {% endstepper %}

#### Managing Zones

* **View Zones**: `/zone list` - Lists all zones in chat
* **Delete Zone**: Use UI or `/zone delete [name]`
* **Teleport to Zone**: Click "Teleport" button in UI
* **Update Zone**: Modify zone in UI (future feature)

### Zone Types

#### Safe Zone

* Weapons automatically holstered
* PvP disabled
* Players are invincible
* No weapon violations logged

#### Law Zone

* Warning given when weapon drawn
* Punishment applied after warning time
* Fine, jail, or auto-holster punishment
* Violations logged to Discord

#### Custom Zone

* Custom rules can be applied
* Base zone functionality
* Can be extended with custom rules

### For Players

* **Automatic Detection**: Zones are automatically detected when entering
* **Notifications**: Receive notifications when entering/exiting zones
* **Weapon Auto-Holster**: Weapons automatically holstered in safe zones
* **Visual Markers**: See zone boundaries with colored markers
* **3D Text**: Zone names displayed above zones when nearby

## 🔧 Advanced Settings

### Adding Custom Zone Rules

```lua
Config.CustomRules = {
    no_horses = {
        enabled = true,
        message = "No horses allowed in this area"
    },
    no_looting = {
        enabled = true,
        message = "Looting is prohibited here"
    },
    no_running = {
        enabled = true,
        message = "Please walk, don't run"
    }
}
```

### Changing Marker Types

Common marker types for RedM:

* `1` - Circle marker
* `23` - Hollow circle
* `25` - Ring marker
* `28` - Cylinder marker (recommended)

### Framework Detection

The script automatically detects your framework. Supported frameworks:

* **VORP**: `vorp_core`
* **RedEM**: `redem_roleplay` or `redem`
* **RSG**: `rsg-core`
* **Standalone**: Uses ACE permissions

### Admin Permissions (Standalone)

```cfg
# In server.cfg, add ACE permissions:
add_ace group.admin "safezones.admin" allow
```

## 🎨 UI Features

### Admin Interface

* **Western Theme**: Beautiful old western design
* **Zone List**: View all active zones
* **Zone Creation**: Easy zone creation form
* **Zone Management**: Delete, teleport, and manage zones
* **Real-time Coordinates**: Get your current coordinates
* **Visual Indicators**: Color-coded zone types

### Zone Notifications

* **Enter Notification**: Shows when entering a zone
* **Exit Notification**: Shows when leaving a zone
* **Zone Type Badges**: Visual indicators for zone types
* **Western Design**: Matches admin UI theme

## 📊 Zone Storage

Zones are stored in `zones.json` file in the resource folder. Structure:

```json
[
    {
        "name": "Valentine",
        "type": "law",
        "x": -278.4,
        "y": 806.3,
        "z": 119.3,
        "radius": 150.0,
        "blip": true,
        "rules": []
    }
]
```

## 🐛 Troubleshooting

### Common Issues

<details>

<summary>Zones Not Loading</summary>

* Check `zones.json` file exists and is valid JSON
* Check console for error messages
* Verify zones.json is in resource folder

</details>

<details>

<summary>Markers Not Showing</summary>

* Check `Config.DrawZones = true`
* Verify marker type is correct (try type 28)
* Check `Config.DrawDistance` is large enough
* Ensure you're within draw distance

</details>

<details>

<summary>Weapons Not Auto-Holstering</summary>

* Check `Config.SafeZoneWeaponsDisabled = true`
* Verify you're actually in a safe zone
* Check framework detection is working

</details>

<details>

<summary>Admin Commands Not Working</summary>

* Verify admin group in `Config.AdminGroups`
* Check framework admin detection
* For standalone, verify ACE permissions

</details>

<details>

<summary>Discord Webhook Not Working</summary>

* Verify webhook URL is correct
* Check Discord permissions
* Ensure `Config.LogPunishments = true`

</details>

<details>

<summary>Framework Not Detected</summary>

* Check framework resource is started
* Verify framework name matches exactly
* Check console for detection messages

</details>

<details>

<summary>UI Not Opening</summary>

* Check resource is started
* Verify `fxmanifest.lua` is correct
* Check F8 console for errors
* Ensure NUI files are in `nui/` folder

</details>

## 📝 Commands

| Command               | Permission | Description                     |
| --------------------- | ---------- | ------------------------------- |
| `/zone create [type]` | Admin      | Create zone at current position |
| `/zone delete [name]` | Admin      | Delete a zone                   |
| `/zone list`          | Admin      | List all zones                  |
| `/zoneui`             | Admin      | Open admin management UI        |

## 🔄 Framework Functions

### Server Functions

* `Framework.IsAdmin(source)` - Check if player is admin
* `Framework.RemoveMoney(source, amount)` - Remove money from player
* `Framework.SendToJail(source, time)` - Send player to jail
* `Framework.Notify(source, message, type)` - Send notification

### Client Functions

* Automatic weapon holster detection
* Zone entry/exit detection
* 3D marker rendering
* UI management

## 🎯 Performance Optimization

The script includes performance optimizations:

* **Debounced Zone Rendering**: Prevents excessive re-renders
* **Zone Caching**: Only updates when zones change
* **Efficient DOM Manipulation**: Uses DocumentFragment for better performance
* **Event Delegation**: Single event listener for zone actions
* **CSS Optimizations**: Hardware-accelerated animations
* **Render Optimization**: Only renders zones within draw distance

## 🔐 Security

* Server-side permission checks
* Admin-only zone creation/deletion
* Framework-based admin detection
* ACE permission support for standalone
* Input validation on zone data

## 📄 File Structure

```
coderanch-safezones/
├── client.lua          # Client-side logic
├── server.lua          # Server-side logic
├── config.lua          # Configuration file
├── framework.lua       # Framework compatibility
├── fxmanifest.lua     # Resource manifest
├── zones.json         # Zone storage (auto-generated)
├── nui/
│   ├── index.html     # UI HTML
│   ├── style.css      # UI styling
│   └── script.js      # UI logic
└── README.md          # This file
```

## 🎨 UI Customization

{% stepper %}
{% step %}

### Colors

Edit CSS variables in `nui/style.css` to change colors.
{% endstep %}

{% step %}

### Fonts

Change Google Fonts imports in `nui/index.html` to update fonts.
{% endstep %}

{% step %}

### Layout

Modify HTML structure in `nui/index.html` to change layout.
{% endstep %}

{% step %}

### Icons

The UI uses Lucide icons (change in `nui/script.js`).
{% endstep %}
{% endstepper %}

## 🔄 Updates

### v1.0.0

* Initial release
* Safe zone and law zone support
* Admin management UI
* Multi-framework support
* Discord integration
* Visual markers and 3D text
* Performance optimizations

## 💡 Tips

* Zone Placement: Place zone centers at ground level for best marker visibility
* Radius Size: Recommended radius: 100-300 meters
* Zone Overlap: Zones can overlap, player enters the first zone detected
* Marker Distance: Increase `DrawDistance` for larger zones
* Performance: Disable `DrawZones` if not needed for better performance
* Backup Zones: Backup `zones.json` file regularly
* Admin UI: Use `/zoneui` for easier zone management
* Testing: Test zones in safe areas before deploying

***

**Note**: This script is developed for RedM Beta version. Incompatibilities may occur in RedM's official release.

**Support**: For issues or questions, contact CodeRanch support.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://coderanch-redm-store.gitbook.io/coderanch-redm-store-docs/coderanch-zone-system.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
