or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

extensions.mdindex.mdmath-functions.mdmatrices.mdquaternions.mdrandom-noise.mdtransformations.mdutilities.mdvectors.md

random-noise.mddocs/

0

# Random and Noise Functions

1

2

Random number generation and noise functions for procedural content generation, simulation, and creative applications. These functions provide various probability distributions and noise algorithms commonly used in graphics and game development.

3

4

## Capabilities

5

6

### Random Number Generation

7

8

Functions for generating random values with different probability distributions.

9

10

```python { .api }

11

def setSeed(seed):

12

"""

13

Set the random seed for reproducible random sequences.

14

15

Args:

16

seed: Integer seed value

17

18

Example:

19

glm.setSeed(12345) # Set specific seed for reproducible results

20

"""

21

22

def linearRand(min_val, max_val):

23

"""

24

Generate random value(s) with uniform distribution.

25

26

Args:

27

min_val: Minimum value (scalar or vector)

28

max_val: Maximum value (same type as min_val)

29

30

Returns:

31

Random value(s) uniformly distributed between min_val and max_val

32

33

Example:

34

rand_float = glm.linearRand(0.0, 1.0) # Random float [0, 1]

35

rand_vec3 = glm.linearRand(glm.vec3(-1), glm.vec3(1)) # Random vec3 in cube

36

rand_int = glm.linearRand(-10, 10) # Random integer [-10, 10]

37

"""

38

39

def gaussRand(mean, deviation):

40

"""

41

Generate random value(s) with Gaussian (normal) distribution.

42

43

Args:

44

mean: Mean value of the distribution (scalar or vector)

45

deviation: Standard deviation (scalar or vector)

46

47

Returns:

48

Random value(s) with Gaussian distribution

49

50

Example:

51

normal_val = glm.gaussRand(0.0, 1.0) # Standard normal distribution

52

normal_vec = glm.gaussRand(glm.vec3(5), glm.vec3(2)) # Mean=5, σ=2

53

"""

54

```

55

56

### Geometric Random Functions

57

58

Functions for generating random points within geometric shapes and surfaces.

59

60

```python { .api }

61

def circularRand(radius):

62

"""

63

Generate random point on a circle's circumference.

64

65

Args:

66

radius: Circle radius (scalar)

67

68

Returns:

69

vec2 representing random point on circle circumference

70

71

Example:

72

point_on_circle = glm.circularRand(5.0) # Random point on radius=5 circle

73

"""

74

75

def sphericalRand(radius):

76

"""

77

Generate random point on a sphere's surface.

78

79

Args:

80

radius: Sphere radius (scalar)

81

82

Returns:

83

vec3 representing random point on sphere surface

84

85

Example:

86

point_on_sphere = glm.sphericalRand(3.0) # Random point on radius=3 sphere

87

"""

88

89

def diskRand(radius):

90

"""

91

Generate random point inside a disk (2D circle).

92

93

Args:

94

radius: Disk radius (scalar)

95

96

Returns:

97

vec2 representing random point inside disk

98

99

Example:

100

point_in_disk = glm.diskRand(2.0) # Random point inside radius=2 disk

101

"""

102

103

def ballRand(radius):

104

"""

105

Generate random point inside a ball (3D sphere).

106

107

Args:

108

radius: Ball radius (scalar)

109

110

Returns:

111

vec3 representing random point inside ball

112

113

Example:

114

point_in_ball = glm.ballRand(4.0) # Random point inside radius=4 ball

115

"""

116

```

117

118

### Noise Functions

119

120

Procedural noise functions for generating smooth, pseudo-random patterns commonly used in procedural generation and texture synthesis.

121

122

```python { .api }

123

def perlin(p):

124

"""

125

Generate Perlin noise value.

126

127

Args:

128

p: Input coordinate (scalar, vec2, vec3, or vec4)

129

130

Returns:

131

Noise value typically in range [-1, 1]

132

133

Note:

134

Perlin noise provides smooth, natural-looking random variation

135

with consistent gradients across space

136

137

Example:

138

noise_1d = glm.perlin(5.3) # 1D noise

139

noise_2d = glm.perlin(glm.vec2(x, y)) # 2D noise for textures

140

noise_3d = glm.perlin(glm.vec3(x, y, z)) # 3D noise for volumetric effects

141

"""

142

143

def simplex(p):

144

"""

145

Generate simplex noise value.

146

147

Args:

148

p: Input coordinate (scalar, vec2, vec3, or vec4)

149

150

Returns:

151

Noise value typically in range [-1, 1]

152

153

Note:

154

Simplex noise is an improved version of Perlin noise with

155

better visual characteristics and performance in higher dimensions

156

157

Example:

158

simplex_2d = glm.simplex(glm.vec2(x * 0.01, y * 0.01)) # Terrain height

159

simplex_3d = glm.simplex(glm.vec3(x, y, time)) # Animated noise

160

"""

161

```

162

163

### Usage Examples

164

165

```python

166

from pyglm import glm

167

import random

168

169

# === Basic Random Generation ===

170

171

# Set seed for reproducible results

172

glm.setSeed(42)

173

174

# Generate random floats

175

random_float = glm.linearRand(0.0, 1.0) # [0, 1]

176

random_range = glm.linearRand(-5.0, 5.0) # [-5, 5]

177

178

# Generate random vectors

179

random_position = glm.linearRand(glm.vec3(-10), glm.vec3(10)) # Random position in cube

180

random_color = glm.linearRand(glm.vec3(0), glm.vec3(1)) # Random RGB color

181

182

# Generate random integers

183

random_int = glm.linearRand(-100, 100) # Random integer

184

185

# Gaussian (normal) distribution

186

normal_value = glm.gaussRand(50.0, 10.0) # Mean=50, std_dev=10

187

height_variation = glm.gaussRand(0.0, 0.5) # Small height variation

188

189

# === Geometric Random Sampling ===

190

191

# Random points on geometric shapes

192

circle_point = glm.circularRand(1.0) # Unit circle circumference

193

sphere_point = glm.sphericalRand(5.0) # Sphere surface (radius=5)

194

195

# Random points inside shapes

196

disk_point = glm.diskRand(3.0) # Inside disk (radius=3)

197

ball_point = glm.ballRand(2.0) # Inside ball (radius=2)

198

199

# === Procedural Generation Examples ===

200

201

# Random terrain height generation

202

def generate_terrain_height(x, z, octaves=4):

203

height = 0.0

204

amplitude = 1.0

205

frequency = 0.01

206

207

for i in range(octaves):

208

noise_value = glm.perlin(glm.vec2(x * frequency, z * frequency))

209

height += noise_value * amplitude

210

211

amplitude *= 0.5 # Reduce amplitude for each octave

212

frequency *= 2.0 # Increase frequency for each octave

213

214

return height

215

216

# Generate terrain for a 100x100 grid

217

terrain_heights = []

218

for x in range(100):

219

row = []

220

for z in range(100):

221

height = generate_terrain_height(x, z)

222

row.append(height)

223

terrain_heights.append(row)

224

225

# Random particle system

226

class ParticleSystem:

227

def __init__(self, count):

228

self.particles = []

229

for _ in range(count):

230

# Random position in sphere

231

position = glm.ballRand(10.0)

232

233

# Random velocity on sphere surface (outward)

234

velocity = glm.sphericalRand(glm.linearRand(1.0, 5.0))

235

236

# Random color

237

color = glm.linearRand(glm.vec3(0.5), glm.vec3(1.0))

238

239

# Random lifetime

240

lifetime = glm.gaussRand(3.0, 0.5) # 3±0.5 seconds

241

242

self.particles.append({

243

'position': position,

244

'velocity': velocity,

245

'color': color,

246

'lifetime': max(0.1, lifetime) # Ensure positive lifetime

247

})

248

249

# Create particle system

250

particles = ParticleSystem(1000)

251

252

# === Noise-Based Procedural Generation ===

253

254

# 2D texture generation using Perlin noise

255

def generate_noise_texture(width, height, scale=0.1):

256

texture = []

257

for y in range(height):

258

row = []

259

for x in range(width):

260

# Generate noise value

261

noise_coord = glm.vec2(x * scale, y * scale)

262

noise_value = glm.perlin(noise_coord)

263

264

# Convert from [-1, 1] to [0, 1]

265

normalized = (noise_value + 1.0) * 0.5

266

267

# Convert to grayscale color

268

color = glm.vec3(normalized)

269

row.append(color)

270

texture.append(row)

271

272

return texture

273

274

# Generate 256x256 noise texture

275

noise_texture = generate_noise_texture(256, 256, 0.02)

276

277

# Animated noise for effects

278

def animated_noise(position, time):

279

# Use time as third dimension for animation

280

coord = glm.vec3(position.x * 0.05, position.y * 0.05, time * 0.1)

281

return glm.simplex(coord)

282

283

# Generate animated fire effect

284

def fire_effect(x, y, time):

285

# Multiple noise octaves for complex fire pattern

286

base_coord = glm.vec2(x * 0.01, y * 0.01 - time * 0.5) # Rising motion

287

288

# Large-scale noise for overall shape

289

large_noise = glm.perlin(base_coord) * 0.5

290

291

# Medium-scale noise for detail

292

medium_coord = base_coord * 3.0

293

medium_noise = glm.perlin(medium_coord) * 0.3

294

295

# Small-scale noise for fine detail

296

small_coord = base_coord * 8.0

297

small_noise = glm.perlin(small_coord) * 0.2

298

299

# Combine noises

300

combined_noise = large_noise + medium_noise + small_noise

301

302

# Add height-based falloff (fire dies out upward)

303

height_factor = max(0.0, 1.0 - (y * 0.01))

304

305

return combined_noise * height_factor

306

307

# === Random Distribution Utilities ===

308

309

# Generate random colors with specific hue

310

def random_color_with_hue(base_hue, saturation=1.0, value=1.0):

311

# Vary hue slightly

312

hue_variation = glm.gaussRand(0.0, 0.1)

313

final_hue = base_hue + hue_variation

314

315

# Add slight variations to saturation and value

316

final_sat = glm.clamp(saturation + glm.gaussRand(0.0, 0.1), 0.0, 1.0)

317

final_val = glm.clamp(value + glm.gaussRand(0.0, 0.1), 0.0, 1.0)

318

319

# Convert HSV to RGB (simplified - actual implementation would need HSV conversion)

320

return glm.vec3(final_sat * final_val) # Simplified for example

321

322

# Generate random movement patterns

323

class RandomWalker:

324

def __init__(self, start_position):

325

self.position = start_position

326

self.velocity = glm.vec3(0)

327

328

def update(self, dt):

329

# Add random acceleration

330

random_force = glm.sphericalRand(1.0) * glm.linearRand(0.5, 2.0)

331

self.velocity += random_force * dt

332

333

# Apply drag

334

self.velocity *= 0.95

335

336

# Update position

337

self.position += self.velocity * dt

338

339

def get_position(self):

340

return self.position

341

342

# Create random walker

343

walker = RandomWalker(glm.vec3(0, 0, 0))

344

345

# Simulate movement

346

for frame in range(100):

347

walker.update(1.0/60.0) # 60 FPS

348

position = walker.get_position()

349

# Use position for rendering...

350

351

# === Noise-Based Terrain Generation ===

352

353

def generate_island_terrain(x, z, island_size=50.0):

354

# Distance from center for island falloff

355

center_distance = glm.length(glm.vec2(x, z)) / island_size

356

island_falloff = 1.0 - glm.smoothstep(0.0, 1.0, center_distance)

357

358

# Multiple octaves of Perlin noise

359

detail_scale = 0.02

360

large_features = glm.perlin(glm.vec2(x * detail_scale, z * detail_scale)) * 10.0

361

362

medium_scale = 0.05

363

medium_features = glm.perlin(glm.vec2(x * medium_scale, z * medium_scale)) * 5.0

364

365

fine_scale = 0.1

366

fine_features = glm.perlin(glm.vec2(x * fine_scale, z * fine_scale)) * 2.0

367

368

# Combine noise layers

369

total_height = large_features + medium_features + fine_features

370

371

# Apply island falloff

372

final_height = total_height * island_falloff

373

374

# Ensure minimum ocean level

375

return max(final_height, -2.0)

376

377

# Generate island heightmap

378

island_size = 100

379

heightmap = []

380

for z in range(-island_size, island_size + 1):

381

row = []

382

for x in range(-island_size, island_size + 1):

383

height = generate_island_terrain(x, z)

384

row.append(height)

385

heightmap.append(row)

386

```

387

388

### Best Practices

389

390

1. **Seeding**: Use `setSeed()` at the start of your application for reproducible results during development

391

2. **Noise Scaling**: Scale noise coordinates appropriately - smaller values (0.01-0.1) give smoother results

392

3. **Octave Layering**: Combine multiple noise octaves at different frequencies for more natural-looking results

393

4. **Performance**: Cache noise values when possible, as noise functions can be computationally expensive

394

5. **Range Mapping**: Remember that noise functions typically return values in [-1, 1] - map to your desired range

395

6. **Geometric Sampling**: Use appropriate geometric random functions for uniform distribution on surfaces and within volumes