import bpy
import numpy as np

def register_props():
    bpy.types.Scene.gravity_strength = bpy.props.FloatProperty(
        name="重力定数 G",
        default=1.0,
        min=0.1,
        max=5.0,
        step=0.1,
        precision=2
    )

def calculate_orbit(context):
    G = context.scene.gravity_strength
    M = 1000
    pos = np.array([8.0, 0.0])
    vel = np.array([0.0, 10.0])
    dt = 0.01
    steps = 400
    positions = []

    bpy.ops.object.select_all(action='SELECT')
    bpy.ops.object.delete(use_global=False)

    bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=(0, 0, 0))
    sun = bpy.context.object
    sun.name = "Sun"

    mat = bpy.data.materials.new("SunMat")
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links

    for node in nodes:
        nodes.remove(node)

    tex_image = nodes.new(type='ShaderNodeTexImage')
    img_path = "/Users/saitokaren/koeki/git/InforSystem/blend/sun_texture.jpg"
    tex_image.image = bpy.data.images.load(img_path)

    emission = nodes.new(type='ShaderNodeEmission')
    material_output = nodes.new(type='ShaderNodeOutputMaterial')

    tex_image.location = (-300, 0)
    emission.location = (0, 0)
    material_output.location = (300, 0)

    links.new(tex_image.outputs['Color'], emission.inputs['Color'])
    links.new(emission.outputs['Emission'], material_output.inputs['Surface'])

    sun.data.materials.append(mat)

    bpy.ops.object.light_add(type='SUN', location=(0, 0, 0))
    light = bpy.context.object
    light.data.energy = 3
    light.rotation_euler = (np.radians(135), 0, 0)

    bpy.ops.mesh.primitive_uv_sphere_add(radius=0.3, location=(pos[0], pos[1], 0))
    earth = bpy.context.object
    earth.name = "Earth"

    mat = bpy.data.materials.new("EarthMat")
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links

    for node in nodes:
        nodes.remove(node)

    tex_image = nodes.new(type='ShaderNodeTexImage')
    img_path = "/Users/saitokaren/koeki/git/InforSystem/blend/earth_texture.jpg"
    tex_image.image = bpy.data.images.load(img_path)

    bsdf = nodes.new(type='ShaderNodeBsdfPrincipled')
    material_output = nodes.new(type='ShaderNodeOutputMaterial')

    links.new(tex_image.outputs['Color'], bsdf.inputs['Base Color'])
    links.new(bsdf.outputs['BSDF'], material_output.inputs['Surface'])

    earth.data.materials.append(mat)

    scene = context.scene
    scene.frame_start = 1
    scene.frame_end = steps
    rotation_z_earth = 0.0
    rotation_z_sun = 0.0

    for frame in range(1, steps + 1):
        r_vec = -pos
        dist = np.linalg.norm(r_vec)
        acc = G * M * r_vec / dist**3
        vel += acc * dt
        pos += vel * dt
        positions.append(pos.copy())

        earth.location = (pos[0], pos[1], 0)
        earth.keyframe_insert(data_path="location", frame=frame)

        rotation_z_earth += 0.1
        earth.rotation_euler = (0, 0, rotation_z_earth)
        earth.keyframe_insert(data_path="rotation_euler", frame=frame)

        rotation_z_sun += 0.05
        sun.rotation_euler = (0, 0, rotation_z_sun)
        sun.keyframe_insert(data_path="rotation_euler", frame=frame)

class GravityOnlyPanel(bpy.types.Panel):
    bl_label = "重力定数で軌道観察"
    bl_idname = "VIEW3D_PT_gravity_only"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = '重力定数'

    def draw(self, context):
        layout = self.layout
        layout.prop(context.scene, "gravity_strength")
        layout.operator("orbit.recalc", text="再計算")
        layout.operator("screen.animation_play", text="▶")

class RecalcOrbitOperator(bpy.types.Operator):
    bl_idname = "orbit.recalc"
    bl_label = "軌道を再計算"

    def execute(self, context):
        calculate_orbit(context)
        self.report({'INFO'}, "軌道を再計算しました")
        return {'FINISHED'}

classes = [GravityOnlyPanel, RecalcOrbitOperator]

def register():
    for cls in classes:
        bpy.utils.register_class(cls)
    register_props()

def unregister():
    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)
    del bpy.types.Scene.gravity_strength

if __name__ == "__main__":
    register()
    calculate_orbit(bpy.context)
