diff --git a/Lab3/.gitignore b/Lab3/.gitignore new file mode 100644 index 0000000..b1dff0d --- /dev/null +++ b/Lab3/.gitignore @@ -0,0 +1,45 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Kotlin ### +.kotlin + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/Lab3/.idea/.gitignore b/Lab3/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/Lab3/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/Lab3/.idea/gradle.xml b/Lab3/.idea/gradle.xml new file mode 100644 index 0000000..2a65317 --- /dev/null +++ b/Lab3/.idea/gradle.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/Lab3/.idea/kotlinc.xml b/Lab3/.idea/kotlinc.xml new file mode 100644 index 0000000..c224ad5 --- /dev/null +++ b/Lab3/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/Lab3/.idea/misc.xml b/Lab3/.idea/misc.xml new file mode 100644 index 0000000..5cd9a10 --- /dev/null +++ b/Lab3/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Lab3/.idea/vcs.xml b/Lab3/.idea/vcs.xml new file mode 100644 index 0000000..6c0b863 --- /dev/null +++ b/Lab3/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Lab3/build.gradle.kts b/Lab3/build.gradle.kts new file mode 100644 index 0000000..5b88868 --- /dev/null +++ b/Lab3/build.gradle.kts @@ -0,0 +1,52 @@ +plugins { + kotlin("jvm") version "2.0.21" + application +} + +group = "org.example" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +val lwjglVersion = "3.3.3" +val lwjglNatives = "natives-linux" // Для NixOS используем стандартные Linux-нативы + +dependencies { + testImplementation(kotlin("test")) + implementation(platform("org.lwjgl:lwjgl-bom:$lwjglVersion")) + + // Основные LWJGL модули + implementation("org.lwjgl:lwjgl") + implementation("org.lwjgl:lwjgl-glfw") + implementation("org.lwjgl:lwjgl-opengl") + + // Дополнительные модули + implementation("org.lwjgl:lwjgl-stb") + implementation("org.lwjgl:lwjgl-nanovg") + implementation("org.lwjgl:lwjgl-nfd") + implementation("org.lwjgl:lwjgl-openal") + implementation("org.joml:joml:1.10.5") + + // Нативные библиотеки + runtimeOnly("org.lwjgl:lwjgl::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-glfw::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-opengl::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-stb::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-nanovg::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-nfd::$lwjglNatives") + runtimeOnly("org.lwjgl:lwjgl-openal::$lwjglNatives") +} + +tasks.test { + useJUnitPlatform() +} + +application { + mainClass.set("org.exampl.MainKt") // Укажите главный класс +} + +kotlin { + jvmToolchain(21) +} \ No newline at end of file diff --git a/Lab3/gradle.properties b/Lab3/gradle.properties new file mode 100644 index 0000000..7fc6f1f --- /dev/null +++ b/Lab3/gradle.properties @@ -0,0 +1 @@ +kotlin.code.style=official diff --git a/Lab3/gradle/wrapper/gradle-wrapper.jar b/Lab3/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/Lab3/gradle/wrapper/gradle-wrapper.jar differ diff --git a/Lab3/gradle/wrapper/gradle-wrapper.properties b/Lab3/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..4ce871c --- /dev/null +++ b/Lab3/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun May 11 12:45:28 MSK 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/Lab3/gradlew b/Lab3/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/Lab3/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/Lab3/gradlew.bat b/Lab3/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/Lab3/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/Lab3/settings.gradle.kts b/Lab3/settings.gradle.kts new file mode 100644 index 0000000..ce68df5 --- /dev/null +++ b/Lab3/settings.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} +rootProject.name = "Lab3" + diff --git a/Lab3/shell.nix b/Lab3/shell.nix new file mode 100644 index 0000000..b391947 --- /dev/null +++ b/Lab3/shell.nix @@ -0,0 +1,32 @@ +{ pkgs ? import {} }: + +pkgs.mkShell { + buildInputs = [ + pkgs.jdk21 + pkgs.gradle + pkgs.libGL + pkgs.glfw + pkgs.xorg.libX11 + pkgs.xorg.libXcursor + pkgs.xorg.libXrandr + pkgs.xorg.libXi + pkgs.mesa + ]; + + shellHook = '' + export JAVA_HOME="${pkgs.jdk21}" + export PATH="${pkgs.gradle}/bin:$PATH" + export LD_LIBRARY_PATH="${ + pkgs.lib.makeLibraryPath [ + pkgs.libGL + pkgs.glfw + pkgs.xorg.libX11 + pkgs.xorg.libXcursor + pkgs.xorg.libXrandr + pkgs.xorg.libXi + pkgs.mesa + ] + }:$LD_LIBRARY_PATH" + ''; +} + diff --git a/Lab3/src/main/kotlin/Main.kt b/Lab3/src/main/kotlin/Main.kt new file mode 100644 index 0000000..1f5fc74 --- /dev/null +++ b/Lab3/src/main/kotlin/Main.kt @@ -0,0 +1,341 @@ +package org.exampl + +import org.lwjgl.glfw.GLFW.* +import org.lwjgl.opengl.GL +import org.lwjgl.opengl.GL20.* +import org.lwjgl.opengl.GL30.* +import org.lwjgl.system.MemoryUtil.* +import java.nio.FloatBuffer +import kotlin.math.* + +class AtomModelShader { + private var window: Long = 0 + private var isRunning = false + private var shaderProgram = 0 + private var vao = 0 + private var vbo = 0 + + // Параметры камеры + private var cameraDistance = 15.0f + private var cameraAngleX = 30.0f + private var cameraAngleY = 45.0f + + // Параметры атома + private val nucleusRadius = 1.2f + private val electronRadius = 0.4f + private val orbitRadii = floatArrayOf(4.0f, 6.0f, 8.0f) + private var rotationAngle = 0.0f + + fun run() { + init() + loop() + cleanup() + } + + private fun init() { + if (!glfwInit()) throw IllegalStateException("Unable to initialize GLFW") + + glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE) + glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE) + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3) + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3) + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE) + + window = glfwCreateWindow(1000, 800, "3D Atom Model with Shaders", NULL, NULL) + ?: throw RuntimeException("Failed to create GLFW window") + + glfwMakeContextCurrent(window) + GL.createCapabilities() + + // Инициализация шейдеров + initShaders() + initBuffers() + + glEnable(GL_DEPTH_TEST) + glClearColor(0.1f, 0.1f, 0.15f, 1.0f) + + glfwSetFramebufferSizeCallback(window) { _, width, height -> + glViewport(0, 0, width, height) + } + + glfwShowWindow(window) + isRunning = true + setupControls() + } + + private fun initShaders() { + // Вершинный шейдер + val vertexShader = """ + #version 330 core + layout (location = 0) in vec3 aPos; + layout (location = 1) in vec3 aNormal; + + out vec3 Normal; + out vec3 FragPos; + + uniform mat4 model; + uniform mat4 view; + uniform mat4 projection; + + void main() { + gl_Position = projection * view * model * vec4(aPos, 1.0); + FragPos = vec3(model * vec4(aPos, 1.0)); + Normal = mat3(transpose(inverse(model))) * aNormal; + } + """.trimIndent() + + // Фрагментный шейдер + val fragmentShader = """ + #version 330 core + out vec4 FragColor; + + in vec3 Normal; + in vec3 FragPos; + + uniform vec3 objectColor; + uniform vec3 lightPos; + uniform vec3 lightColor; + uniform vec3 viewPos; + + void main() { + // Ambient + float ambientStrength = 0.1; + vec3 ambient = ambientStrength * lightColor; + + // Diffuse + vec3 norm = normalize(Normal); + vec3 lightDir = normalize(lightPos - FragPos); + float diff = max(dot(norm, lightDir), 0.0); + vec3 diffuse = diff * lightColor; + + // Specular + float specularStrength = 0.5; + vec3 viewDir = normalize(viewPos - FragPos); + vec3 reflectDir = reflect(-lightDir, norm); + float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32); + vec3 specular = specularStrength * spec * lightColor; + + vec3 result = (ambient + diffuse + specular) * objectColor; + FragColor = vec4(result, 1.0); + } + """.trimIndent() + + shaderProgram = glCreateProgram() + val vs = compileShader(vertexShader, GL_VERTEX_SHADER) + val fs = compileShader(fragmentShader, GL_FRAGMENT_SHADER) + + glAttachShader(shaderProgram, vs) + glAttachShader(shaderProgram, fs) + glLinkProgram(shaderProgram) + + if (glGetProgrami(shaderProgram, GL_LINK_STATUS) == GL_FALSE) { + throw RuntimeException("Shader linking failed: ${glGetProgramInfoLog(shaderProgram)}") + } + + glDeleteShader(vs) + glDeleteShader(fs) + } + + private fun compileShader(source: String, type: Int): Int { + val shader = glCreateShader(type) + glShaderSource(shader, source) + glCompileShader(shader) + + if (glGetShaderi(shader, GL_COMPILE_STATUS) == GL_FALSE) { + throw RuntimeException("Shader compilation failed: ${glGetShaderInfoLog(shader)}") + } + + return shader + } + + private fun initBuffers() { + vao = glGenVertexArrays() + vbo = glGenBuffers() + + glBindVertexArray(vao) + glBindBuffer(GL_ARRAY_BUFFER, vbo) + + // Создаем сферу для ядра и электронов + val sphereData = createSphereData(1.0f, 32, 32) + glBufferData(GL_ARRAY_BUFFER, sphereData, GL_STATIC_DRAW) + + // Позиции вершин (0) + glVertexAttribPointer(0, 3, GL_FLOAT, false, 6 * Float.SIZE_BYTES, 0) + glEnableVertexAttribArray(0) + + // Нормали (1) + glVertexAttribPointer(1, 3, GL_FLOAT, false, 6 * Float.SIZE_BYTES, 3 * Float.SIZE_BYTES.toLong()) + glEnableVertexAttribArray(1) + + glBindBuffer(GL_ARRAY_BUFFER, 0) + glBindVertexArray(0) + } + + private fun createSphereData(radius: Float, sectors: Int, stacks: Int): FloatBuffer { + val vertices = mutableListOf() + val sectorStep = 2 * PI.toFloat() / sectors + val stackStep = PI.toFloat() / stacks + + for (i in 0..stacks) { + val stackAngle = PI.toFloat() / 2 - i * stackStep + val xy = radius * cos(stackAngle) + val z = radius * sin(stackAngle) + + for (j in 0..sectors) { + val sectorAngle = j * sectorStep + val x = xy * cos(sectorAngle) + val y = xy * sin(sectorAngle) + + // Нормаль + val nx = x / radius + val ny = y / radius + val nz = z / radius + + vertices.add(x) + vertices.add(y) + vertices.add(z) + vertices.add(nx) + vertices.add(ny) + vertices.add(nz) + } + } + + val buffer = org.lwjgl.BufferUtils.createFloatBuffer(vertices.size) + vertices.forEach { buffer.put(it) } + buffer.flip() + return buffer + } + + private fun setupControls() { + glfwSetKeyCallback(window) { _, key, _, action, _ -> + when { + key == GLFW_KEY_ESCAPE && action == GLFW_PRESS -> glfwSetWindowShouldClose(window, true) + action == GLFW_PRESS || action == GLFW_REPEAT -> handleKeyPress(key) + } + } + + glfwSetScrollCallback(window) { _, _, yOffset -> + cameraDistance = (cameraDistance - yOffset).coerceIn(5.0, 30.0).toFloat() + } + + glfwSetCursorPosCallback(window) { _, xPos, yPos -> + if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) { + cameraAngleY += xPos.toFloat() * 0.2f + cameraAngleX = (cameraAngleX + yPos.toFloat() * 0.1f).coerceIn(5f, 85f) + } + } + } + + private fun handleKeyPress(key: Int) { + when (key) { + GLFW_KEY_W -> cameraAngleX -= 2f + GLFW_KEY_S -> cameraAngleX += 2f + GLFW_KEY_A -> cameraAngleY -= 2f + GLFW_KEY_D -> cameraAngleY += 2f + GLFW_KEY_Q -> cameraDistance += 0.5f + GLFW_KEY_E -> cameraDistance -= 0.5f + } + } + + private fun loop() { + while (isRunning && !glfwWindowShouldClose(window)) { + glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) + + // Обновление угла вращения + rotationAngle += 0.6f + + // Активация шейдера + glUseProgram(shaderProgram) + + // Настройка камеры + val view = createViewMatrix() + val projection = createProjectionMatrix() + + // Установка uniform-переменных + glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "view"), false, view) + glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), false, projection) + glUniform3f(glGetUniformLocation(shaderProgram, "lightPos"), 10f, 10f, 10f) + glUniform3f(glGetUniformLocation(shaderProgram, "lightColor"), 1f, 1f, 1f) + glUniform3f(glGetUniformLocation(shaderProgram, "viewPos"), + 0f, 0f, cameraDistance) + + // Отрисовка ядра + drawNucleus() + + // Отрисовка электронов + drawElectrons() + + glfwSwapBuffers(window) + glfwPollEvents() + } + } + + private fun createViewMatrix(): FloatBuffer { + val matrix = org.joml.Matrix4f() + matrix.rotateX(cameraAngleX * (PI.toFloat() / 180f)) + matrix.rotateY(cameraAngleY * (PI.toFloat() / 180f)) + matrix.translate(0f, 0f, -cameraDistance) + return matrix.get(FloatArray(16)).toFloatBuffer() + } + + private fun createProjectionMatrix(): FloatBuffer { + val matrix = org.joml.Matrix4f() + matrix.perspective(45f * (PI.toFloat() / 180f), 1000f / 800f, 0.1f, 100f) + return matrix.get(FloatArray(16)).toFloatBuffer() + } + + private fun drawNucleus() { + val model = org.joml.Matrix4f().scale(nucleusRadius) + glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), false, model.get(FloatArray(16)).toFloatBuffer()) + glUniform3f(glGetUniformLocation(shaderProgram, "objectColor"), 0.3f, 0.5f, 1.0f) + + glBindVertexArray(vao) + glDrawArrays(GL_TRIANGLE_STRIP, 0, 32 * 32 * 6) + glBindVertexArray(0) + } + + private fun drawElectrons() { + val colors = arrayOf( + floatArrayOf(1f, 0.2f, 0.2f), // Красный + floatArrayOf(0.2f, 1f, 0.2f), // Зеленый + floatArrayOf(0.4f, 0.4f, 1f) // Синий + ) + + for (i in 0 until 3) { + val angle = rotationAngle * (1 + i * 0.3f) + val x = orbitRadii[i] * cos(angle.toDouble()).toFloat() + val z = orbitRadii[i] * sin(angle.toDouble()).toFloat() + val y = orbitRadii[i] * 0.3f * sin(angle.toDouble() * 1.5).toFloat() + + val model = org.joml.Matrix4f() + .translate(x, y, z) + .scale(electronRadius) + + glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), false, model.get(FloatArray(16)).toFloatBuffer()) + glUniform3f(glGetUniformLocation(shaderProgram, "objectColor"), colors[i][0], colors[i][1], colors[i][2]) + + glBindVertexArray(vao) + glDrawArrays(GL_TRIANGLE_STRIP, 0, 32 * 32 * 6) + glBindVertexArray(0) + } + } + + private fun FloatArray.toFloatBuffer(): FloatBuffer { + val buffer = org.lwjgl.BufferUtils.createFloatBuffer(size) + buffer.put(this) + buffer.flip() + return buffer + } + + private fun cleanup() { + glDeleteVertexArrays(vao) + glDeleteBuffers(vbo) + glDeleteProgram(shaderProgram) + glfwDestroyWindow(window) + glfwTerminate() + } +} + +fun main() { + AtomModelShader().run() +} \ No newline at end of file