Sure! I'll update your Pygame script to:
- Display the Source of Light: Enhance the visualization of the light source (the sun) by adding a glowing effect to indicate its brightness.
- Add a Wet Effect on the Sphere's Surface: Implement a specular highlight to simulate a wet or glossy surface. This effect can be toggled on and off using the
E key.
Below is the complete updated code with these enhancements:
import pygame
import math
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("3D Sphere with Realistic Lighting and Sun Rays")
# Clock for controlling frame rate
CLOCK = pygame.time.Clock()
FPS = 60 # Increased frame rate for smoother visuals
# Sphere properties
SPHERE_RADIUS = 200
SPHERE_CENTER = (WIDTH // 2, HEIGHT // 2 + 50) # Slightly lower to center vertically
# Light properties
# Initial light direction (unit vector)
light_dir = [1, 1, -1]
# Normalize the light direction
length = math.sqrt(light_dir[0]**2 + light_dir[1]**2 + light_dir[2]**2)
light_dir = [component / length for component in light_dir]
# Light movement step (radians)
LIGHT_STEP = 0.05 # Increased for smoother rotation
# Colors
BACKGROUND_COLOR = (10, 10, 50)
SPHERE_COLOR = (255, 165, 0) # Orange
SUN_COLOR = (255, 255, 200) # Soft yellow for the sun
RAY_COLOR = (255, 255, 200) # Same as sun for consistency
SPECULAR_COLOR = (255, 255, 255) # White for specular highlights
SUN_GLOW_COLOR = (255, 255, 180, 100) # Semi-transparent for glow
# Wet effect toggle
wet_effect = False
def normalize(v):
length = math.sqrt(sum([coord ** 2 for coord in v]))
if length == 0:
return [0, 0, 0]
return [coord / length for coord in v]
def handle_input():
global light_dir, wet_effect
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
wet_effect = not wet_effect # Toggle wet effect on/off
keys = pygame.key.get_pressed()
# Adjust light direction based on arrow keys and W/S keys
# Using spherical coordinates for light direction adjustments
if keys[pygame.K_LEFT]:
# Rotate light direction to the left around Y axis
angle = LIGHT_STEP
new_x = light_dir[0] * math.cos(angle) - light_dir[2] * math.sin(angle)
new_z = light_dir[0] * math.sin(angle) + light_dir[2] * math.cos(angle)
light_dir[0], light_dir[2] = new_x, new_z
if keys[pygame.K_RIGHT]:
# Rotate light direction to the right around Y axis
angle = -LIGHT_STEP
new_x = light_dir[0] * math.cos(angle) - light_dir[2] * math.sin(angle)
new_z = light_dir[0] * math.sin(angle) + light_dir[2] * math.cos(angle)
light_dir[0], light_dir[2] = new_x, new_z
if keys[pygame.K_UP]:
# Rotate light direction up around X axis
angle = LIGHT_STEP
new_y = light_dir[1] * math.cos(angle) - light_dir[2] * math.sin(angle)
new_z = light_dir[1] * math.sin(angle) + light_dir[2] * math.cos(angle)
light_dir[1], light_dir[2] = new_y, new_z
if keys[pygame.K_DOWN]:
# Rotate light direction down around X axis
angle = -LIGHT_STEP
new_y = light_dir[1] * math.cos(angle) - light_dir[2] * math.sin(angle)
new_z = light_dir[1] * math.sin(angle) + light_dir[2] * math.cos(angle)
light_dir[1], light_dir[2] = new_y, new_z
if keys[pygame.K_w]:
# Rotate light direction forward around Z axis
angle = LIGHT_STEP
new_x = light_dir[0] * math.cos(angle) - light_dir[1] * math.sin(angle)
new_y = light_dir[0] * math.sin(angle) + light_dir[1] * math.cos(angle)
light_dir[0], light_dir[1] = new_x, new_y
if keys[pygame.K_s]:
# Rotate light direction backward around Z axis
angle = -LIGHT_STEP
new_x = light_dir[0] * math.cos(angle) - light_dir[1] * math.sin(angle)
new_y = light_dir[0] * math.sin(angle) + light_dir[1] * math.cos(angle)
light_dir[0], light_dir[1] = new_x, new_y
# Normalize light direction after adjustments
light_dir = normalize(light_dir)
def draw_sphere():
# Define view direction (assuming orthographic projection)
view_dir = [0, 0, 1] # Camera looking towards positive Z
# Shininess exponent for specular highlights
shininess = 50 # Higher value for smaller, sharper highlights
for y in range(SPHERE_CENTER[1] - SPHERE_RADIUS, SPHERE_CENTER[1] + SPHERE_RADIUS):
dy = y - SPHERE_CENTER[1]
for x in range(SPHERE_CENTER[0] - SPHERE_RADIUS, SPHERE_CENTER[0] + SPHERE_RADIUS):
dx = x - SPHERE_CENTER[0]
distance_sq = dx * dx + dy * dy
if distance_sq <= SPHERE_RADIUS * SPHERE_RADIUS:
# Calculate z coordinate on the sphere
try:
dz = math.sqrt(SPHERE_RADIUS * SPHERE_RADIUS - distance_sq)
except:
dz = 0 # Handle floating point errors
# Surface normal
normal = [dx, dy, dz]
normal = normalize(normal)
# Lambertian shading (diffuse)
dot = normal[0] * light_dir[0] + normal[1] * light_dir[1] + normal[2] * light_dir[2]
dot = max(dot, 0) # Clamp to [0,1]
shading = dot
# Specular shading (wet effect)
specular = 0
if wet_effect:
# Reflect light direction around the normal
reflection = [
2 * normal[0] * dot - light_dir[0],
2 * normal[1] * dot - light_dir[1],
2 * normal[2] * dot - light_dir[2],
]
reflection = normalize(reflection)
# Dot product with view direction
spec_angle = reflection[0] * view_dir[0] + reflection[1] * view_dir[1] + reflection[2] * view_dir[2]
spec_angle = max(spec_angle, 0)
specular = (spec_angle ** shininess)
# Combine diffuse and specular shading
total_shading = shading + specular * 0.5 # Adjust specular weight as needed
total_shading = min(total_shading, 1) # Clamp to [0,1]
# Apply shading to sphere color
color = (
min(int(SPHERE_COLOR[0] * total_shading), 255),
min(int(SPHERE_COLOR[1] * total_shading), 255),
min(int(SPHERE_COLOR[2] * total_shading), 255),
)
# Draw the pixel
SCREEN.set_at((x, y), color)
def draw_sun_and_rays():
# Determine the sun's position based on the light direction
# Place the sun at a distance outside the screen in the direction opposite to light_dir
sun_distance = 1000 # Arbitrary large distance to place sun outside the screen
sun_x = int(SPHERE_CENTER[0] - light_dir[0] * sun_distance)
sun_y = int(SPHERE_CENTER[1] - light_dir[1] * sun_distance)
# Draw sun rays
NUM_RAYS = 30 # Increased number of rays for better coverage
RAY_LENGTH = 150 # Length of each ray
angle_between_rays = (2 * math.pi) / NUM_RAYS
for i in range(NUM_RAYS):
angle = i * angle_between_rays
# Calculate ray direction based on light_dir and ensure rays emanate from the sun
ray_dir_x = light_dir[0] + 0.3 * math.cos(angle) # Adding spread to rays
ray_dir_y = light_dir[1] + 0.3 * math.sin(angle)
ray_dir = normalize([ray_dir_x, ray_dir_y, light_dir[2]])
# Starting point is the sun's position
start_pos = (sun_x, sun_y)
# Ending point is towards the sphere with some spread
end_x = sun_x + int(ray_dir[0] * RAY_LENGTH)
end_y = sun_y + int(ray_dir[1] * RAY_LENGTH)
end_pos = (end_x, end_y)
# Draw the ray as a line
pygame.draw.line(SCREEN, RAY_COLOR, start_pos, end_pos, 2)
# Draw the sun as a glowing circle
SUN_RADIUS = 30
# Create a surface for the glow with per-pixel alpha
glow_surface = pygame.Surface((SUN_RADIUS*4, SUN_RADIUS*4), pygame.SRCALPHA)
pygame.draw.circle(glow_surface, SUN_GLOW_COLOR, (SUN_RADIUS*2, SUN_RADIUS*2), SUN_RADIUS*2)
pygame.draw.circle(glow_surface, SUN_COLOR, (SUN_RADIUS*2, SUN_RADIUS*2), SUN_RADIUS)
# Blit the glow onto the main screen
SCREEN.blit(glow_surface, (sun_x - SUN_RADIUS*2, sun_y - SUN_RADIUS*2), special_flags=pygame.BLEND_RGBA_ADD)
# Draw the sun's core
pygame.draw.circle(SCREEN, SUN_COLOR, (sun_x, sun_y), SUN_RADIUS)
def main():
global wet_effect
while True:
handle_input()
# Clear screen
SCREEN.fill(BACKGROUND_COLOR)
# Draw sun rays and sun
draw_sun_and_rays()
# Draw sphere with current lighting
draw_sphere()
# Optional: Display toggle status on screen
font = pygame.font.SysFont(None, 24)
status_text = f"Wet Effect: {'On' if wet_effect else 'Off'} (Toggle with 'E')"
text_surface = font.render(status_text, True, (255, 255, 255))
SCREEN.blit(text_surface, (10, 10))
# Update the display
pygame.display.flip()
# Maintain frame rate
CLOCK.tick(FPS)
if __name__ == "__main__":
main()
Enhancements Explained
-
Displaying the Source of Light (Sun)
- Glowing Effect: To create a more realistic sun, a glowing effect is added using a semi-transparent surface. This is achieved by creating a separate
glow_surface with per-pixel alpha transparency and blitting it onto the main SCREEN using additive blending (pygame.BLEND_RGBA_ADD). This makes the sun appear to emit light into the scene.
- Increase Number of Rays: The number of sun rays has been increased to
30 for better coverage and a more radiant appearance.
-
Wet Effect on the Sphere's Surface
- Specular Highlights: A specular component is added to simulate the reflection of light, which gives the appearance of a wet or glossy surface. This is based on the Phong reflection model where the specular highlight depends on the viewer's position and the light reflection.
- Toggle Functionality: The wet effect can be toggled on and off by pressing the
E key. The current status of the wet effect is displayed in the top-left corner of the screen.
- Implementation Details:
- Specular Calculation: For each pixel on the sphere, the reflection of the light direction around the normal is calculated. The dot product of this reflection with the view direction determines the intensity of the specular highlight.
- Shading Combination: The total shading is a combination of the diffuse (Lambertian) shading and the specular highlight. The specular component is scaled appropriately to ensure it contributes realistically to the overall shading.
-
User Interface Enhancements
- Frame Rate: The frame rate has been increased from
30 FPS to 60 FPS for smoother animations.
- Status Display: The current status of the wet effect (On/Off) is displayed on the screen, providing immediate feedback to the user when toggling the effect.
How to Use the Updated Script
- Control the Light Source:
- Rotate Light Direction:
- Left Arrow (
←): Rotate light direction to the left around the Y-axis.
- Right Arrow (
→): Rotate light direction to the right around the Y-axis.
- Up Arrow (
↑): Rotate light direction upward around the X-axis.
- Down Arrow (
↓): Rotate light direction downward around the X-axis.
W Key: Rotate light direction forward around the Z-axis.
S Key: Rotate light direction backward around the Z-axis.
- Toggle Wet Effect:
E Key: Toggle the wet effect (specular highlights) on and off. The current status is displayed on the screen.
Running the Script
Ensure you have Pygame installed. If not, you can install it using pip:
pip install pygame
Save the updated script to a file, for example, wet_sphere.py, and run it using Python:
python wet_sphere.py
You should see a 3D sphere with realistic lighting and sun rays. Use the arrow keys and W/S to adjust the light direction, and press E to toggle the wet effect on and off.
Final Notes
- Performance Considerations: Pixel-by-pixel rendering in Pygame can be computationally intensive, especially at higher resolutions and frame rates. If you experience performance issues, consider optimizing the drawing process or reducing the screen resolution.
- Further Enhancements:
- Dynamic Lighting: Implement multiple light sources or dynamic light movement.
- Interactive Controls: Add more interactive controls for adjusting the sphere's properties, such as radius or color.
- Enhanced Visual Effects: Incorporate additional effects like shadows, reflections, or environment mapping for greater realism.
Feel free to customize and expand upon this script to suit your project's needs!