跳转至

其实这一期也是和上一期一起的,只不过个人确实没怎么写过Python以及脚本,这部分也不太影响前一章的内容,因此和前一期分开记录了。

CheckPython.py

  • install:接受一个参数带代表包名,调用pip命令行工具安装指定包
  • valudate:接受一个参数,通过key检查该包,若有缺失则重新下载
  • ValidatePackages:调用、检查两个包
    import subprocess
    import pkg_resources
    
    
    
    def install(package):
        print(f"Installing {package} module...")
        subprocess.check_call(['python', '-m', 'pip', 'install', package])
    
    
    
    def ValidatePackage(package):
        required = { package }
        installed = {pkg.key for pkg in pkg_resources.working_set}
        missing = required - installed
        if missing:
            install(package)
    
    
    
    def ValidatePackages():
        ValidatePackage('requests')
        ValidatePackage('fake-useragent')
        
    

Utils.py

  1. DownloadFile(url, filepath)
    • 这个函数接受两个参数:url(文件的下载链接)和filepath(文件保存的本地路径)。
    • 使用fake_useragent库生成一个随机的用户代理(User-Agent),以模拟不同的浏览器请求,这有助于绕过一些基于用户代理的访问限制。
    • 发起HTTP GET请求到指定的url,并设置请求头中的User-Agent
    • 如果响应头中包含content-length,则会显示下载进度;如果不包含,则直接写入文件。
    • 通过requests库的iter_content方法,可以以块的方式下载文件,这样可以在下载大文件时减少内存使用。
    • 计算下载速度,并实时显示下载进度和速度。
  2. YesOrNo()
    • 这个函数用于获取用户的是/否响应。
    • 它不断循环,直到用户输入y(表示是)或n(表示否)。
    • 用户的输入会被转换为小写并去除空白,然后检查第一个字符是否为yn
      import requests
      import sys
      import time
      from fake_useragent import UserAgent
      
      def DownloadFile(url, filepath):
          with open(filepath, 'wb') as f:
              ua = UserAgent()
              headers = {'User-Agent': ua.chrome}
              response = requests.get(url, headers=headers, stream=True)
              total = response.headers.get('content-length')
              if total is None:
                  f.write(response.content)
              else:
                  downloaded = 0
                  total = int(total)
                  startTime = time.time()
                  for data in response.iter_content(chunk_size=max(int(total/1000), 1024*1024)):
                      downloaded += len(data)
                      f.write(data)
                      done = int(50*downloaded/total)
                      percentage = (downloaded / total) * 100
                      elapsedTime = time.time() - startTime
                      avgKBPerSecond = (downloaded / 1024) / elapsedTime
                      avgSpeedString = '{:.2f} KB/s'.format(avgKBPerSecond)
                      if (avgKBPerSecond > 1024):
                          avgMBPerSecond = avgKBPerSecond / 1024
                          avgSpeedString = '{:.2f} MB/s'.format(avgMBPerSecond)
                      sys.stdout.write('\r[{}{}] {:.2f}% ({})     '.format('█' * done, '.' * (50-done), percentage, avgSpeedString))
                      sys.stdout.flush()
          sys.stdout.write('\n')
      
      def YesOrNo():
          while True:
              reply = str(input('[Y/N]: ')).lower().strip()
              if reply[:1] == 'y':
                  return True
              if reply[:1] == 'n':
                  return False
      

Vulkan.py

  • InstallVulkanSDK:阿坝州高压部分vulkanSDK
  • InstallVulkanPrompt:安装提示
  • CheckVulkanSDK:检查vulkansdk,再检查版本,提示你是否安装
  • debug libs检查
    import os
    
    import subprocess
    
    import sys
    
    from pathlib import Path
    
    import Utils
    
    from io import BytesIO
    
    from urllib.request import urlopen
    
    from zipfile import ZipFile
    
    VULKAN_SDK = os.environ.get('VULKAN_SDK')
    
    VULKAN_SDK_INSTALLER_URL = 'https://sdk.lunarg.com/sdk/download/1.2.170.0/windows/vulkan_sdk.exe'
    
    HAZEL_VULKAN_VERSION = '1.2.170.0'
    
    VULKAN_SDK_EXE_PATH = 'CryDust/vendor/VulkanSDK/VulkanSDK.exe'
    
    
    
    def InstallVulkanSDK():
    
        print('Downloading {} to {}'.format(VULKAN_SDK_INSTALLER_URL, VULKAN_SDK_EXE_PATH))
    
        Utils.DownloadFile(VULKAN_SDK_INSTALLER_URL, VULKAN_SDK_EXE_PATH)
    
        print("Done!")
    
        print("Running Vulkan SDK installer...")
    
        os.startfile(os.path.abspath(VULKAN_SDK_EXE_PATH))
    
        print("Re-run this script after installation")
    
    
    
    
    def InstallVulkanPrompt():
    
        print("Would you like to install the Vulkan SDK?")
    
        install = Utils.YesOrNo()
    
        if (install):
    
            InstallVulkanSDK()
    
            quit()
    
    
    
    
    def CheckVulkanSDK():
    
        if (VULKAN_SDK is None):
    
            print("You don't have the Vulkan SDK installed!")
    
            InstallVulkanPrompt()
    
            return False
    
        elif (HAZEL_VULKAN_VERSION not in VULKAN_SDK):
    
            print(f"Located Vulkan SDK at {VULKAN_SDK}")
    
            print(f"You don't have the correct Vulkan SDK version! (CryDust requires {HAZEL_VULKAN_VERSION})")
    
            InstallVulkanPrompt()
    
            return False
    
        print(f"Correct Vulkan SDK located at {VULKAN_SDK}")
    
        return True
    
    VulkanSDKDebugLibsURL = 'https://files.lunarg.com/SDK-1.2.170.0/VulkanSDK-1.2.170.0-DebugLibs.zip'
    
    OutputDirectory = "CryDust/vendor/VulkanSDK"
    
    TempZipFile = f"{OutputDirectory}/VulkanSDK.zip"
    
    
    
    
    def CheckVulkanSDKDebugLibs():
    
        shadercdLib = Path(f"{OutputDirectory}/Lib/shaderc_sharedd.lib")
    
        if (not shadercdLib.exists()):
    
            print(f"No Vulkan SDK debug libs found. (Checked {shadercdLib})")
    
            print("Downloading", VulkanSDKDebugLibsURL)
    
            with urlopen(VulkanSDKDebugLibsURL) as zipresp:
    
                with ZipFile(BytesIO(zipresp.read())) as zfile:
    
                    zfile.extractall(OutputDirectory)
    
        print(f"Vulkan SDK debug libs located at {OutputDirectory}")
    
        return True
    

Setup.py

  • 检查python
  • 检查vulkan
  • 构建项目
    import os
    import subprocess
    import CheckPython
    # Make sure everything we need is installed
    CheckPython.ValidatePackages()
    import Vulkan
    # Change from Scripts directory to root
    os.chdir('../')
    if (not Vulkan.CheckVulkanSDK()):
        print("Vulkan SDK not installed.")
    if (not Vulkan.CheckVulkanSDKDebugLibs())
        print("Vulkan SDK debug libs not found.")
    print("Running premake...")
    subprocess.call(["vendor/premake/bin/premake5.exe", "vs2022"])
    

Setup.bat

启动

@echo off
python Setup.py
PAUSE

运行图片

重做

下一个commit就重做了...

验证设置脚本重制(#438) 创建VulkanSDK目录 如果它不存在的话把设置放在不同的类中添加一个进度条到解压缩函数 因为解压缩可以花费相当多的时间用于调试工具删除UserAgent对python的要求(它不是最新的) 要求使用pip安装python的前提条件,而不是强行打破已经存在的python安装不使用pip(例如:anaconda)

Premake的检查和安装

虽然Premake5...本身是有安装的

不过可以让他不上传到Github上,用的时候再检查和安装

import sys

import os

from pathlib import Path

import Utils

class PremakeConfiguration:

    premakeVersion = "5.0.0-alpha16"

    premakeZipUrls = f"https://github.com/premake/premake-core/releases/download/v{premakeVersion}/premake-{premakeVersion}-windows.zip"

    premakeLicenseUrl = "https://raw.githubusercontent.com/premake/premake-core/master/LICENSE.txt"

    premakeDirectory = "./vendor/premake/bin"

    @classmethod

    def Validate(cls):

        if (not cls.CheckIfPremakeInstalled()):

            print("Premake is not installed.")

            return False

        print(f"Correct Premake located at {os.path.abspath(cls.premakeDirectory)}")

        return True

    @classmethod

    def CheckIfPremakeInstalled(cls):

        premakeExe = Path(f"{cls.premakeDirectory}/premake5.exe");

        if (not premakeExe.exists()):

            return cls.InstallPremake()

        return True

    @classmethod

    def InstallPremake(cls):

        permissionGranted = False

        while not permissionGranted:

            reply = str(input("Premake not found. Would you like to download Premake {0:s}? [Y/N]: ".format(cls.premakeVersion))).lower().strip()[:1]

            if reply == 'n':

                return False

            permissionGranted = (reply == 'y')

        premakePath = f"{cls.premakeDirectory}/premake-{cls.premakeVersion}-windows.zip"

        print("Downloading {0:s} to {1:s}".format(cls.premakeZipUrls, premakePath))

        Utils.DownloadFile(cls.premakeZipUrls, premakePath)

        print("Extracting", premakePath)

        Utils.UnzipFile(premakePath, deleteZipFile=True)

        print(f"Premake {cls.premakeVersion} has been downloaded to '{cls.premakeDirectory}'")

        premakeLicensePath = f"{cls.premakeDirectory}/LICENSE.txt"

        print("Downloading {0:s} to {1:s}".format(cls.premakeLicenseUrl, premakeLicensePath))

        Utils.DownloadFile(cls.premakeLicenseUrl, premakeLicensePath)

        print(f"Premake License file has been downloaded to '{cls.premakeDirectory}'")

        return True