Add AIServer, character art pipeline, and Art package boot integration.

Bring in MaleExplorer assets/shaders, model tooling and Hunyuan updates, plus boot/YooAsset Art package support.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
udx
2026-09-21 17:06:59 +08:00
co-authored by Cursor
parent b7a0bbcb89
commit 6550b8df4b
121 changed files with 313260 additions and 113 deletions
+5
View File
@@ -49,6 +49,11 @@ AIClient/HybridCLRData/
AIClient/Bundles/
Tools/cdn_root/
# AIServer
AIServer/build/
AIServer/data/*.db
AIServer/data/*.db-*
# Crash / OS
*.stackdump
Thumbs.db
@@ -12,6 +12,7 @@ namespace AOT.Boot
public string CdnRoot;
public string PackageName;
public ResourcePackage Package;
public string HttpBase;
public string WsUrlTemplate;
public string BuildWsUrl(string pid, string token = null)
@@ -66,6 +66,11 @@ namespace AOT.Boot
_view?.SetProgress(1f);
_view?.SetStatus("热更已启动");
Debug.Log($"[Boot] OK app={ctx.AppVersion} res={ctx.ResVersion} cdn={ctx.CdnRoot}");
// 让热更侧完成首帧生成后再撤掉全屏启动遮罩
yield return null;
yield return null;
_view?.Hide();
}
}
}
@@ -24,6 +24,9 @@ namespace AOT.Boot
[Tooltip("热更 DLL 在包内的定位地址")]
public string HotUpdateDllLocation = "HotUpdate.Runtime";
[Tooltip("登录服 HTTP 根(/register /login)")]
public string HttpBase = "https://game.xworld.ren";
[Tooltip("WebSocket 模板,{pid}/{token} 会被替换")]
public string WsUrlTemplate = "wss://game.xworld.ren/ws?pid={pid}&token={token}";
@@ -74,6 +74,7 @@ namespace AOT.Patch
ResVersion = version.resVersion,
CdnRoot = cdnRoot,
PackageName = _settings.PackageName,
HttpBase = _settings.HttpBase,
WsUrlTemplate = _settings.WsUrlTemplate,
};
@@ -104,6 +104,16 @@ namespace AOT.UI
_fill.color = new Color(0.85f, 0.3f, 0.3f, 1f);
}
public void Hide()
{
gameObject.SetActive(false);
}
public void DestroyUi()
{
Destroy(gameObject);
}
static GameObject CreateUiObject(string name, Transform parent)
{
var go = new GameObject(name, typeof(RectTransform));
@@ -38,3 +38,25 @@ MonoBehaviour:
FilterRuleName: CollectAll
AssetTags: aot
UserData:
- PackageName: Art
PackageDesc: "\u89D2\u8272/\u573A\u666F\u7F8E\u672F"
EnableAddressable: 1
SupportExtensionless: 1
LocationToLower: 0
IncludeAssetGUID: 0
AutoCollectShaders: 1
IgnoreRuleName: NormalIgnoreRule
Groups:
- GroupName: Characters
GroupDesc:
AssetTags: art
ActiveRuleName: EnableGroup
Collectors:
- CollectPath: Assets/Bundles/Characters
CollectorGUID: 9022903d083ef5e48a260c7146d9c3d0
CollectorType: 0
AddressRuleName: AddressByFileName
PackRuleName: PackDirectory
FilterRuleName: CollectAll
AssetTags: art
UserData:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9022903d083ef5e48a260c7146d9c3d0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5de8b303c51073744b95736c9efa04cc
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,109 @@
fileFormatVersion: 2
guid: 4e7306923b3941041b15fc08a96215f4
ModelImporter:
serializedVersion: 22200
internalIDToNameTable: []
externalObjects: {}
materials:
materialImportMode: 0
materialName: 0
materialSearch: 1
materialLocation: 1
animations:
legacyGenerateAnimations: 4
bakeSimulation: 0
resampleCurves: 1
optimizeGameObjects: 0
removeConstantScaleCurves: 0
motionNodeName:
rigImportErrors:
rigImportWarnings:
animationImportErrors:
animationImportWarnings:
animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
importAnimatedCustomProperties: 0
importConstraints: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5
animationScaleError: 0.5
animationWrapMode: 0
extraExposedTransformPaths: []
extraUserProperties: []
clipAnimations: []
isReadable: 0
meshes:
lODScreenPercentages: []
globalScale: 1
meshCompression: 2
addColliders: 0
useSRGBMaterialColor: 1
sortHierarchyByName: 1
importPhysicalCameras: 1
importVisibility: 1
importBlendShapes: 1
importCameras: 1
importLights: 1
nodeNameCollisionStrategy: 1
fileIdsGeneration: 2
swapUVChannels: 0
generateSecondaryUV: 0
useFileUnits: 1
keepQuads: 0
weldVertices: 1
bakeAxisConversion: 0
preserveHierarchy: 0
skinWeightsMode: 0
maxBonesPerVertex: 4
minBoneWeight: 0.001
optimizeBones: 1
meshOptimizationFlags: -1
indexFormat: 0
secondaryUVAngleDistortion: 8
secondaryUVAreaDistortion: 15.000001
secondaryUVHardAngle: 88
secondaryUVMarginMethod: 1
secondaryUVMinLightmapResolution: 40
secondaryUVMinObjectScale: 1
secondaryUVPackMargin: 4
useFileScale: 1
strictVertexDataChecks: 0
tangentSpace:
normalSmoothAngle: 60
normalImportMode: 0
tangentImportMode: 3
normalCalculationMode: 4
legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes: 0
blendShapeNormalImportMode: 1
normalSmoothingSource: 0
referencedClips: []
importAnimation: 1
humanDescription:
serializedVersion: 3
human: []
skeleton: []
armTwist: 0.5
foreArmTwist: 0.5
upperLegTwist: 0.5
legTwist: 0.5
armStretch: 0.05
legStretch: 0.05
feetSpacing: 0
globalScale: 1
rootMotionBoneName:
hasTranslationDoF: 0
hasExtraRoot: 0
skeletonHasParents: 1
lastHumanDescriptionAvatarSource: {instanceID: 0}
autoGenerateAvatarMappingIfUnspecified: 1
animationType: 2
humanoidOversampling: 1
avatarSetup: 0
addHumanoidExtraRootOnlyWhenUsingAvatar: 1
importBlendShapeDeformPercent: 1
remapMaterialsIfMaterialImportModeIsNone: 0
additionalBone: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,135 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 8
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: MaleExplorer
m_Shader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
m_Parent: {fileID: 0}
m_ModifiedSerializedProperties: 0
m_ValidKeywords:
- _METALLICSPECGLOSSMAP
- _NORMALMAP
m_InvalidKeywords: []
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap:
RenderType: Opaque
disabledShaderPasses: []
m_LockedProperties:
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BaseMap:
m_Texture: {fileID: 2800000, guid: c579bc2bc4f3d1d4ca6357e196647a1c, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 2800000, guid: bf759bb4be79da040a36f6323376395f, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: c579bc2bc4f3d1d4ca6357e196647a1c, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 2800000, guid: ff662381d729e41439bba157f4fd986e, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 2800000, guid: 677ccffc54808d74ca91daefb7ff4d82, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_Lightmaps:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_LightmapsInd:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_ShadowMasks:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Ints: []
m_Floats:
- _AlphaClip: 0
- _AlphaToMask: 0
- _Blend: 0
- _BlendModePreserveSpecular: 1
- _BumpScale: 1
- _ClearCoatMask: 0
- _ClearCoatSmoothness: 0
- _Cull: 2
- _Cutoff: 0.5
- _DetailAlbedoMapScale: 1
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _DstBlendAlpha: 0
- _EnvironmentReflections: 1
- _GlossMapScale: 0
- _Glossiness: 0
- _GlossyReflections: 0
- _Metallic: 0
- _OcclusionStrength: 1
- _Parallax: 0.005
- _QueueOffset: 0
- _ReceiveShadows: 1
- _Smoothness: 0.45
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _SrcBlendAlpha: 1
- _Surface: 0
- _WorkflowMode: 1
- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
m_BuildTextureStacks: []
--- !u!114 &2338677793862294356
MonoBehaviour:
m_ObjectHideFlags: 11
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
m_Name:
m_EditorClassIdentifier:
version: 7
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 35936ffb5462d8540b0cac78a2667a68
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,166 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &4818435621640061303
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 671829433351447729}
- component: {fileID: 5968824582601252609}
- component: {fileID: 8346968313850684562}
m_Layer: 0
m_Name: ShadowDisc
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &671829433351447729
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4818435621640061303}
serializedVersion: 2
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0.02, z: 0}
m_LocalScale: {x: 0.7, y: 0.015, z: 0.7}
m_ConstrainProportionsScale: 0
m_Children: []
m_Father: {fileID: 7751142206369119175}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!33 &5968824582601252609
MeshFilter:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4818435621640061303}
m_Mesh: {fileID: 10206, guid: 0000000000000000e000000000000000, type: 0}
--- !u!23 &8346968313850684562
MeshRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4818435621640061303}
m_Enabled: 1
m_CastShadows: 0
m_ReceiveShadows: 1
m_DynamicOccludee: 1
m_StaticShadowCaster: 0
m_MotionVectors: 1
m_LightProbeUsage: 1
m_ReflectionProbeUsage: 1
m_RayTracingMode: 2
m_RayTraceProcedural: 0
m_RenderingLayerMask: 1
m_RendererPriority: 0
m_Materials:
- {fileID: 0}
m_StaticBatchInfo:
firstSubMesh: 0
subMeshCount: 0
m_StaticBatchRoot: {fileID: 0}
m_ProbeAnchor: {fileID: 0}
m_LightProbeVolumeOverride: {fileID: 0}
m_ScaleInLightmap: 1
m_ReceiveGI: 1
m_PreserveUVs: 1
m_IgnoreNormalsForChartDetection: 0
m_ImportantGI: 0
m_StitchLightmapSeams: 1
m_SelectedEditorRenderState: 3
m_MinimumChartSize: 4
m_AutoUVMaxDistance: 0.5
m_AutoUVMaxAngle: 89
m_LightmapParameters: {fileID: 0}
m_SortingLayerID: 0
m_SortingLayer: 0
m_SortingOrder: 0
m_AdditionalVertexStreams: {fileID: 0}
--- !u!1001 &7789872454374415404
PrefabInstance:
m_ObjectHideFlags: 0
serializedVersion: 2
m_Modification:
serializedVersion: 3
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalScale.x
value: 1.6454926
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalScale.y
value: 1.6454926
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalScale.z
value: 1.6454926
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalPosition.x
value: -0
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalPosition.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalPosition.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalRotation.w
value: 0.7071067
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalRotation.x
value: -0.7071068
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalRotation.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalRotation.z
value: -0
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalEulerAnglesHint.x
value: 0
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalEulerAnglesHint.y
value: 0
objectReference: {fileID: 0}
- target: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_LocalEulerAnglesHint.z
value: 0
objectReference: {fileID: 0}
- target: {fileID: -7511558181221131132, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_Materials.Array.data[0]
value:
objectReference: {fileID: 2100000, guid: 35936ffb5462d8540b0cac78a2667a68, type: 2}
- target: {fileID: 919132149155446097, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
propertyPath: m_Name
value: MaleExplorer
objectReference: {fileID: 0}
m_RemovedComponents: []
m_RemovedGameObjects: []
m_AddedGameObjects:
- targetCorrespondingSourceObject: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
insertIndex: -1
addedObject: {fileID: 671829433351447729}
m_AddedComponents: []
m_SourcePrefab: {fileID: 100100000, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
--- !u!4 &7751142206369119175 stripped
Transform:
m_CorrespondingSourceObject: {fileID: -8679921383154817045, guid: 4e7306923b3941041b15fc08a96215f4, type: 3}
m_PrefabInstance: {fileID: 7789872454374415404}
m_PrefabAsset: {fileID: 0}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: ed5026598de73104fbe7b7b800be4c69
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 MiB

@@ -0,0 +1,153 @@
fileFormatVersion: 2
guid: 677ccffc54808d74ca91daefb7ff4d82
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: WebGL
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 MiB

@@ -0,0 +1,153 @@
fileFormatVersion: 2
guid: c579bc2bc4f3d1d4ca6357e196647a1c
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: WebGL
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

@@ -0,0 +1,153 @@
fileFormatVersion: 2
guid: ff662381d729e41439bba157f4fd986e
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: WebGL
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 MiB

@@ -0,0 +1,153 @@
fileFormatVersion: 2
guid: bf759bb4be79da040a36f6323376395f
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 1
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: WebGL
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

@@ -0,0 +1,153 @@
fileFormatVersion: 2
guid: b9a7df2df44db4d48911507f73af520e
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: WebGL
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

@@ -0,0 +1,153 @@
fileFormatVersion: 2
guid: 9cc915e55ce2c8945ba546d42029a5be
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 1
mipBias: 0
wrapU: 0
wrapV: 0
wrapW: 0
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: WebGL
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID:
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3bf2ea9f18173e349a1d79eadbc7b486
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0575d8260b338e84aacc3f29aab3cc72
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2579b7f8d4760cf479310562e005a7b4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8ebefd2fae1b32d488e2acd694285b30
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b0ed5e8d619c68a4fb7a5375f27dc6d8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 614b6a9d6d273944b9fd0edf5139f5ee
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4c47d37ac743dcb46a06ff644f139c36
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,216 @@
Shader "Test/XPbr"
{
Properties
{
[MainColor] _BaseColor("Color", Color) = (1,1,1,1)
[MainTexture] _MainTex("Base (RGB:Albedo A:Alpha/AO)", 2D) = "white" {}
_MixTex("Mix (RG:Normal B:Metallic A:Roughness)", 2D) = "white" {}
// 勾选:A 通道当透明(AlphaTest 裁剪);不勾选:A 通道当 AO
[Toggle(_ALPHATEST_ON)] _AlphaTest("Alpha As Transparency (Clip)", Float) = 0
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Metallic("Metallic", Range(0.0, 1.0)) = 0.8
_Roughness("Roughness", Range(0.0, 1.0)) = 0.6
_AO("AO", Range(0.0, 1.0)) = 1.0
}
SubShader
{
Tags{ "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "IgnoreProjector" = "True" }
Pass
{
Name "ForwardLit"
Tags{ "LightMode" = "UniversalForward" }
ZWrite on
HLSLPROGRAM
// Required to compile gles 2.0 with standard SRP library
// All shaders must be compiled with HLSLcc and currently only gles is not using HLSLcc by default
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN
#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS
#pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH
#pragma shader_feature_local_fragment _ALPHATEST_ON
#pragma vertex vert
#pragma fragment frag
#include "XPbr_Base.hlsl"
Varyings vert(Attributes input)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
// normalWS and tangentWS already normalize.
// this is required to avoid skewing the direction during interpolation
// also required for per-vertex lighting and SH evaluation
VertexNormalInputs normalInput = GetVertexNormalInputs(input.normalOS, input.tangentOS);
half3 vertexLight = VertexLighting(vertexInput.positionWS, normalInput.normalWS);
half fogFactor = 0;
#if !defined(_FOG_FRAGMENT)
fogFactor = ComputeFogFactor(vertexInput.positionCS.z);
#endif
half3 viewDirWS = GetCameraPositionWS() - vertexInput.positionWS;
output.normalWS = half4(normalInput.normalWS, viewDirWS.x);
output.tangentWS = half4(normalInput.tangentWS, viewDirWS.y);
output.bitangentWS = half4(normalInput.bitangentWS, viewDirWS.z);
OUTPUT_LIGHTMAP_UV(input.staticLightmapUV, unity_LightmapST, output.staticLightmapUV);
#ifdef DYNAMICLIGHTMAP_ON
output.dynamicLightmapUV = input.dynamicLightmapUV.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
#endif
OUTPUT_SH(output.normalWS.xyz, output.vertexSH);
#ifdef _ADDITIONAL_LIGHTS_VERTEX
output.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
#else
output.fogFactor = fogFactor;
#endif
output.positionWS = vertexInput.positionWS;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
output.shadowCoord = GetShadowCoord(vertexInput);
#endif
output.positionCS = vertexInput.positionCS;
output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
return output;
}
half4 frag(Varyings input) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(input);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
// 基础贴图:rgb 漫反射,a 透明或 AO(由 _ALPHATEST_ON 决定语义)
half4 albedoAlpha = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv);
// 混合贴图:rg 压缩法线,b 金属度,a 粗糙度
half4 mixTex = SAMPLE_TEXTURE2D(_MixTex, sampler_MixTex, input.uv);
#if defined(_ALPHATEST_ON)
clip(albedoAlpha.a - _Cutoff);
half occlusion = 1.0;
half alpha = albedoAlpha.a;
#else
half occlusion = lerp(1.0, albedoAlpha.a, _AO);
half alpha = 1.0;
#endif
half3 normalTS = DecodeSphereMap(mixTex.rg);
half3 normalWS = TransformTangentToWorld(normalTS,
half3x3(input.tangentWS.xyz, input.bitangentWS.xyz, input.normalWS.xyz));
SurfaceData surfaceData = (SurfaceData)0;
surfaceData.albedo = albedoAlpha.rgb * _BaseColor.rgb;
surfaceData.metallic = saturate(mixTex.b * _Metallic);
surfaceData.smoothness = 1.0 - saturate(mixTex.a * _Roughness);
surfaceData.alpha = alpha;
surfaceData.normalTS = normalTS;
surfaceData.specular = half3(0.0, 0.0, 0.0);
surfaceData.emission = half3(0.0, 0.0, 0.0);
surfaceData.occlusion = occlusion;
surfaceData.clearCoatMask = half(0.0);
surfaceData.clearCoatSmoothness = half(0.0);
InputData inputData;
input.normalWS.rgb = normalWS;//法线需要传入
InitializeInputData(input, surfaceData.normalTS, inputData);
half4 color = UniversalFragmentPBR(inputData, surfaceData);
color.rgb = MixFog(color.rgb, inputData.fogCoord);
return color;
}
ENDHLSL
}
Pass
{
Name "ShadowCaster"
Tags{ "LightMode" = "ShadowCaster" }
ZWrite On
ZTest LEqual
ColorMask 0
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
// -------------------------------------
// Material Keywords
#pragma shader_feature_local_fragment _ALPHATEST_ON
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#include "XPbr_Base.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl"
float3 _LightDirection;
Varyings vert(Attributes input)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
float3 positionWS = TransformObjectToWorld(input.positionOS.xyz);
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
float4 positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, _LightDirection));
#if UNITY_REVERSED_Z
positionCS.z = min(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
#else
positionCS.z = max(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
#endif
output.positionCS = positionCS;
output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
return output;
}
half4 frag(Varyings input) : SV_TARGET
{
#if defined(_ALPHATEST_ON)
half alpha = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv).a;
clip(alpha - _Cutoff);
#endif
return 0;
}
ENDHLSL
}
}
FallBack Off
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: cab897163f45445fa34263d6670bfc9e
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
- _MixTex: {instanceID: 0}
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,145 @@
#ifndef XPBR_LIT_BASE
#define XPBR_LIT_BASE
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SurfaceInput.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
CBUFFER_START(UnityPerMaterial)
float4 _MainTex_ST;
half4 _BaseColor;
half _Cutoff;
half _Metallic;
half _Roughness;
half _AO;
CBUFFER_END
half _XRuntimeAmbientEnabled;
half4 _XRuntimeAmbientSky;
half4 _XRuntimeAmbientEquator;
half4 _XRuntimeAmbientGround;
TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);
TEXTURE2D(_MixTex); SAMPLER(sampler_MixTex);
struct Attributes
{
float4 positionOS : POSITION;
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
float2 texcoord : TEXCOORD0;
float2 staticLightmapUV : TEXCOORD1;
#ifdef DYNAMICLIGHTMAP_ON
float2 dynamicLightmapUV : TEXCOORD2;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct Varyings
{
float2 uv : TEXCOORD0;
DECLARE_LIGHTMAP_OR_SH(staticLightmapUV, vertexSH, 1);
float3 positionWS : TEXCOORD2;
half4 normalWS : TEXCOORD3; // xyz: normal, w: viewDir.x
half4 tangentWS : TEXCOORD4; // xyz: tangent, w: viewDir.y
half4 bitangentWS : TEXCOORD5; // xyz: bitangent, w: viewDir.z
#ifdef _ADDITIONAL_LIGHTS_VERTEX
half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
#else
half fogFactor : TEXCOORD6;
#endif
#ifdef DYNAMICLIGHTMAP_ON
float2 dynamicLightmapUV : TEXCOORD7;
#endif
float4 positionCS : SV_POSITION;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
float4 shadowCoord : TEXCOORD8;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
//解码 RG 两通道球面映射压缩法线(有符号,ModelTranslator 工具编码:enc = n.xy/sqrt(2*(1+n.z)) * 0.5 + 0.5)
float3 DecodeSphereMap(float2 encoded)
{
encoded = encoded * 2.0 - 1.0; //rg 无符号存储,重映射回有符号
float4 nn = float4(encoded, 1, -1);
float l = dot(nn.xyz, -nn.xyw);
nn.z = l;
nn.xy *= sqrt(l);
return nn.xyz * 2 + float3(0, 0, -1);
}
half3 SampleXRuntimeAmbient(half3 normalWS)
{
half y = normalize(normalWS).y;
half useGlobal = step(0.5h, _XRuntimeAmbientEnabled);
half3 sky = lerp(half3(1.353h, 1.452h, 1.568h), _XRuntimeAmbientSky.rgb, useGlobal);
half3 equator = lerp(half3(1.023h, 1.122h, 1.254h), _XRuntimeAmbientEquator.rgb, useGlobal);
half3 ground = lerp(half3(0.561h, 0.528h, 0.462h), _XRuntimeAmbientGround.rgb, useGlobal);
half3 upper = lerp(equator, sky, saturate(y));
half3 lower = lerp(equator, ground, saturate(-y));
return lerp(lower, upper, step(0.0h, y));
}
void InitializeInputData(Varyings input, half3 normalTS, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = input.positionWS;
half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
// 法线已在 frag 中经 TBN 转换到世界空间后写回 input.normalWS
inputData.normalWS = input.normalWS.xyz;
inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS);
inputData.viewDirectionWS = viewDirWS;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
inputData.shadowCoord = input.shadowCoord;
#elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
#ifdef _ADDITIONAL_LIGHTS_VERTEX
inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x);
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
#else
inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactor);
#endif
#if defined(DYNAMICLIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV, input.vertexSH, inputData.normalWS);
#elif defined(LIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.vertexSH, inputData.normalWS);
#else
inputData.bakedGI = SampleSH(inputData.normalWS);
#endif
// 仅在运行时全局环境光开启后才覆盖(Game.cs 设置);否则保留场景自身 SH/光照贴图,
// 避免编辑器预览比 URP Lit 亮(旧写法无条件覆盖成硬编码的高强度三色环境光)
if (_XRuntimeAmbientEnabled > 0.5h)
inputData.bakedGI = SampleXRuntimeAmbient(inputData.normalWS);
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#if defined(DEBUG_DISPLAY)
#if defined(DYNAMICLIGHTMAP_ON)
inputData.dynamicLightmapUV = input.dynamicLightmapUV;
#endif
#if defined(LIGHTMAP_ON)
inputData.staticLightmapUV = input.staticLightmapUV;
#else
inputData.vertexSH = input.vertexSH;
#endif
#endif
}
#endif
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: eca966a3db5d4e8aaa2b324e0dfc9f92
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,322 @@
Shader "XWorld/XTerrain"
{
Properties
{
// 四层颜色贴图
_LayerTex0 ("Layer 0 (R)", 2D) = "white" {}
_LayerTex1 ("Layer 1 (G)", 2D) = "white" {}
_LayerTex2 ("Layer 2 (B)", 2D) = "white" {}
_LayerTex3 ("Layer 3 (A)", 2D) = "white" {}
// 混合贴图(RGBA 分别对应四层权重)
_Control ("Control (RGBA)", 2D) = "white" {}
_Tiling ("Tiling", Float) = 20
_BumpScale("BumpScale", Range(0.0, 10)) = 5
_Roughness("Roughness", Range(0.0, 2.0)) = 0.3
_Metallic("Metallic", Range(0.0, 2.0)) = 0.3
_AO("AO", Range(0.0, 3.0)) = 1.0
//_EmissiveIntensity("EmissiveIntensity", Range(0.0, 2.0)) = 0.3
}
SubShader
{
// Universal Pipeline tag is required. If Universal render pipeline is not set in the graphics settings
// this Subshader will fail. One can add a subshader below or fallback to Standard built-in to make this
// material work with both Universal Render Pipeline and Builtin Unity Pipeline
Tags{ "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "IgnoreProjector" = "True" }
Pass
{
// Lightmode matches the ShaderPassName set in UniversalRenderPipeline.cs. SRPDefaultUnlit and passes with
// no LightMode tag are also rendered by Universal Render Pipeline
Name "ForwardLit"
Tags{ "LightMode" = "UniversalForward" }
ZWrite on
HLSLPROGRAM
// Required to compile gles 2.0 with standard SRP library
// All shaders must be compiled with HLSLcc and currently only gles is not using HLSLcc by default
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN
#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ _MIXTEX_ON
#pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS
#pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH
#pragma vertex vert
#pragma fragment frag
#include "XTerrain_Base.hlsl"
// 声明纹理和采样器
struct AttData
{
float3 normal;
float ao;//获得夹角越狭窄越强
float roughness;//周围高度差越多,越粗糙;颜色越相同越低;
float metallic;//使用平均亮度值
};
float3 _LightDirection;
Varyings vert(Attributes input)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
// normalWS and tangentWS already normalize.
// this is required to avoid skewing the direction during interpolation
// also required for per-vertex lighting and SH evaluation
VertexNormalInputs normalInput = GetVertexNormalInputs(input.normalOS, input.tangentOS);
half3 vertexLight = VertexLighting(vertexInput.positionWS, normalInput.normalWS);
half fogFactor = 0;
#if !defined(_FOG_FRAGMENT)
fogFactor = ComputeFogFactor(vertexInput.positionCS.z);
#endif
output.uv = TRANSFORM_TEX(input.texcoord, _LayerTex0);
// already normalized from normal transform to WS.
// half3 viewDirWS = GetWorldSpaceNormalizeViewDir(vertexInput.positionWS);
// output.normalWS = half4(normalInput.normalWS, viewDirWS.x);//normalInput.normalWS;//
//#if defined(REQUIRES_WORLD_SPACE_TANGENT_INTERPOLATOR) || defined(REQUIRES_TANGENT_SPACE_VIEW_DIR_INTERPOLATOR)
// real sign = input.tangentOS.w * GetOddNegativeScale();
// half4 tangentWS = half4(normalInput.tangentWS.xyz, sign);
//#endif
//#if defined(REQUIRES_WORLD_SPACE_TANGENT_INTERPOLATOR)
// output.tangentWS = tangentWS;
//#endif
half3 viewDirWS = GetCameraPositionWS() - vertexInput.positionWS;
output.normalWS = half4(normalInput.normalWS, viewDirWS.x);
output.tangentWS = half4(normalInput.tangentWS, viewDirWS.y);
output.bitangentWS = half4(normalInput.bitangentWS, viewDirWS.z);
#if defined(REQUIRES_TANGENT_SPACE_VIEW_DIR_INTERPOLATOR)
half3 viewDirTS = GetViewDirectionTangentSpace(tangentWS, output.normalWS, viewDirWS);
output.viewDirTS = viewDirTS;
#endif
OUTPUT_LIGHTMAP_UV(input.staticLightmapUV, unity_LightmapST, output.staticLightmapUV);
#ifdef DYNAMICLIGHTMAP_ON
output.dynamicLightmapUV = input.dynamicLightmapUV.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
#endif
OUTPUT_SH(output.normalWS.xyz, output.vertexSH);
#ifdef _ADDITIONAL_LIGHTS_VERTEX
output.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
#else
output.fogFactor = fogFactor;
#endif
output.positionWS = vertexInput.positionWS;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
output.shadowCoord = GetShadowCoord(vertexInput);
#endif
output.positionCS = vertexInput.positionCS;
return output;
}
//生成灰度图(高度)
float GetGrayColor(half3 color)
{
//return color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;
//return color.r * 0.3 + color.g * 0.59 + color.b * 0.11;
return 0.299f * color.r + 0.587f * color.g + 0.114f * color.b;
}
//生成法线 ao 粗糙度,金属度
AttData GetNormalByGray(float2 uv, half4 col4)
{
AttData ad;
half bumpscale = _BumpScale * _LayerTex0_TexelSize.x;
float2 deltaU = float2(_LayerTex0_TexelSize.x, 0);
float h0 = GetGrayColor(col4.xyz);
float h1_u = GetGrayColor(SAMPLE_TEXTURE2D(_LayerTex0, sampler_LayerTex0, uv - deltaU).rgb);
float h2_u = GetGrayColor(SAMPLE_TEXTURE2D(_LayerTex0, sampler_LayerTex0, uv + deltaU).rgb);
//float3 tangent_u = float3(deltaU.x, 0, (h2_u - h0) * bumpscale);
float3 tangent_u = float3(deltaU.x, 0, (h2_u - h1_u) * bumpscale);
float2 deltaV = float2(0, _LayerTex0_TexelSize.y);
float h1_v = GetGrayColor(SAMPLE_TEXTURE2D(_LayerTex0, sampler_LayerTex0, uv - deltaV).rgb);
float h2_v = GetGrayColor(SAMPLE_TEXTURE2D(_LayerTex0, sampler_LayerTex0, uv + deltaV).rgb);
//float3 tangent_v = float3(0, deltaV.y, (h2_v - h0) * bumpscale);
float3 tangent_v = float3(0, deltaV.y, (h2_v - h1_v) * bumpscale);
//算ao. 两个向量夹角《
float ao;// = 0;
//ad.ao = 0;
ad.normal = normalize(cross(tangent_v, tangent_u));
ad.normal.z *= -1;
float3 vVA = float3(0, deltaV.y, (h2_v - h0) * bumpscale);
float3 vVB = float3(0, deltaV.y, (h1_v - h0) * bumpscale);
float3 VecV = cross(vVA, vVB);
//if (VecV.y > 0)
{//锐角,判断根据锐角度得到夹角深度
ao = saturate(acos(dot(normalize(vVA), normalize(vVB))));
}
float3 vUA = float3(deltaU.x, 0, (h2_u - h0) * bumpscale);
float3 vUB = float3(deltaU.x, 0, (h1_u - h0) * bumpscale);
float3 VecU = cross(vUA, vUB);
//if (VecU.y > 0)
{//锐角,判断根据锐角度得到夹角深度
ad.ao = saturate(acos(dot(normalize(vUA), normalize(vUB))));
}
ad.ao = saturate(1.0f - max(ao, ad.ao) * _AO);
//
//粗糙度
ad.roughness = saturate((abs(h1_u - h0) + abs(h2_u - h0) + abs(h1_v - h0) + abs(h2_v - h0)) + _Roughness);
//金属度
ad.metallic = saturate((h0 + h1_u + h2_u + h1_v + h2_v) / 5 * _Metallic);
return ad;
}
half4 frag(Varyings input) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(input);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
#if defined(_PARALLAXMAP)
#if defined(REQUIRES_TANGENT_SPACE_VIEW_DIR_INTERPOLATOR)
half3 viewDirTS = input.viewDirTS;
#else
half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
half3 viewDirTS = GetViewDirectionTangentSpace(input.tangentWS, input.normalWS, viewDirWS);
#endif
ApplyPerPixelDisplacement(viewDirTS, input.uv);
#endif
// 采样混合权重
half4 splat_control = SAMPLE_TEXTURE2D(_Control, sampler_Control, input.uv);
// 各层颜色采样,使用同一套 UV 并乘以 Tiling
float2 uv = input.uv * _Tiling;
half4 col0 = SAMPLE_TEXTURE2D(_LayerTex0, sampler_LayerTex0, uv);
half4 col1 = SAMPLE_TEXTURE2D(_LayerTex1, sampler_LayerTex1, uv);
half4 col2 = SAMPLE_TEXTURE2D(_LayerTex2, sampler_LayerTex2, uv);
half4 col3 = SAMPLE_TEXTURE2D(_LayerTex3, sampler_LayerTex3, uv);
// 按权重混合
float total = splat_control.r + splat_control.g + splat_control.b + splat_control.a ;
float a = 1 - max(max(splat_control.r, splat_control.g), splat_control.b);
half4 col = col0 * splat_control.r / total
+ col1 * splat_control.g / total
+ col2 * splat_control.b / total
+ col3 * splat_control.a / total ;
//得到法线
AttData ad = GetNormalByGray(uv, col);
half3 normalWS = TransformTangentToWorld(ad.normal,
half3x3(input.tangentWS.xyz, input.bitangentWS.xyz, input.normalWS.xyz));
SurfaceData surfaceData;
surfaceData.specular = half3(0.0, 0.0, 0.0);
surfaceData.albedo = col.rgb;
surfaceData.metallic = ad.metallic;
surfaceData.smoothness = 1.0 - ad.roughness; // 新版URP中smoothness直接控制高光
surfaceData.alpha = col.a;
surfaceData.normalTS = ad.normal;//input.tangentWS;//
//surfaceData.specular = 0;
surfaceData.emission = half3(0.0, 0.0, 0.0);
surfaceData.occlusion = ad.ao;
surfaceData.clearCoatMask = half(0.0);
surfaceData.clearCoatSmoothness = half(0.0);
InputData inputData;
input.normalWS.rgb = normalWS;//法线需要传入
InitializeInputData(input, surfaceData.normalTS, inputData);
half4 color = UniversalFragmentPBR(inputData, surfaceData);
color.rgb = MixFog(color.rgb, inputData.fogCoord);
//color.rgb = ad.ao;//ad.normal;
return color;
}
ENDHLSL
}
Pass
{
Name "ShadowCaster"
Tags{ "LightMode" = "ShadowCaster" }
ZWrite On
ZTest LEqual
Cull[_Cull]
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
// -------------------------------------
// Material Keywords
#pragma shader_feature_local_fragment _ALPHATEST_ON
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#include "XTex_Base.hlsl"
float3 _LightDirection;
Varyings vert(Attributes input)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
float3 positionWS = TransformObjectToWorld(input.positionOS.xyz);
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
float4 positionCS = TransformWorldToHClip(positionWS);
#if UNITY_REVERSED_Z
positionCS.z = min(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
#else
positionCS.z = max(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
#endif
output.positionCS = positionCS;
output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
return output;
}
half4 frag(Varyings input) : SV_TARGET
{
return SampleAlbedoAlpha(input.uv, TEXTURE2D_ARGS(_BaseMap, sampler_BaseMap)).a;
//return 0;
}
ENDHLSL
}
//UsePass "Universal Render Pipeline/Lit/ShadowCaster"
}
FallBack Off
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: c62f5ca63149bac4c8bcb39cf97084a2
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,170 @@
#ifndef XTERRAIN_LIT_BASE
#define XTERRAIN_LIT_BASE
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SurfaceInput.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
CBUFFER_START(UnityPerMaterial)
float4 _LayerTex0_ST;
float4 _LayerTex1_ST;
float4 _LayerTex2_ST;
float4 _LayerTex3_ST;
//half4 _BaseColor;
float _Tiling;
half _BumpScale;
half _Roughness;
half _Metallic;
half _AO;
half _EmissiveIntensity;
half _useCustomGI;
half3 _CustomGIColor;
float4 _LayerTex0_TexelSize;
CBUFFER_END
half _XRuntimeAmbientEnabled;
half4 _XRuntimeAmbientSky;
half4 _XRuntimeAmbientEquator;
half4 _XRuntimeAmbientGround;
//TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);
TEXTURE2D(_LayerTex0);
SAMPLER(sampler_LayerTex0);
TEXTURE2D(_LayerTex1);
SAMPLER(sampler_LayerTex1);
TEXTURE2D(_LayerTex2);
SAMPLER(sampler_LayerTex2);
TEXTURE2D(_LayerTex3);
SAMPLER(sampler_LayerTex3);
TEXTURE2D(_Control);
SAMPLER(sampler_Control);
// 声明变量
struct Attributes
{
float4 positionOS : POSITION;
half4 color : COLOR;
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
float2 texcoord : TEXCOORD0;
float2 staticLightmapUV : TEXCOORD1;
#ifdef DYNAMICLIGHTMAP_ON
float2 dynamicLightmapUV : TEXCOORD2;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct Varyings
{
float2 uv : TEXCOORD0;
DECLARE_LIGHTMAP_OR_SH(staticLightmapUV, vertexSH, 1);
float3 positionWS : TEXCOORD2;
half4 normalWS : TEXCOORD3; // xyz: normal, w: viewDir.x
half4 tangentWS : TEXCOORD4; // xyz: tangent, w: viewDir.y
half4 bitangentWS : TEXCOORD5; // xyz: bitangent, w: viewDir.z
#ifdef _ADDITIONAL_LIGHTS_VERTEX
half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
#else
half fogFactor : TEXCOORD6;
#endif
half4 lightDir : TEXCOORD8;
half4 viewDir : TEXCOORD9;
#ifdef DYNAMICLIGHTMAP_ON
float2 dynamicLightmapUV : TEXCOORD7;
#endif
float4 positionCS : SV_POSITION;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
float4 shadowCoord : TEXCOORD10;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
half3 SampleXRuntimeAmbient(half3 normalWS)
{
half y = normalize(normalWS).y;
half useGlobal = step(0.5h, _XRuntimeAmbientEnabled);
half3 sky = lerp(half3(1.353h, 1.452h, 1.568h), _XRuntimeAmbientSky.rgb, useGlobal);
half3 equator = lerp(half3(1.023h, 1.122h, 1.254h), _XRuntimeAmbientEquator.rgb, useGlobal);
half3 ground = lerp(half3(0.561h, 0.528h, 0.462h), _XRuntimeAmbientGround.rgb, useGlobal);
half3 upper = lerp(equator, sky, saturate(y));
half3 lower = lerp(equator, ground, saturate(-y));
return lerp(lower, upper, step(0.0h, y));
}
void InitializeInputData(Varyings input, half3 normalTS, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = input.positionWS;
half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
#if defined(_NORMALMAP) || defined(_DETAIL)
float sgn = input.tangentWS.w; // should be either +1 or -1
float3 bitangent = sgn * cross(input.normalWS.xyz, input.tangentWS.xyz);
half3x3 tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, input.normalWS.xyz);
#if defined(_NORMALMAP)
inputData.tangentToWorld = tangentToWorld;
#endif
inputData.normalWS = TransformTangentToWorld(normalTS, tangentToWorld);
#else
inputData.normalWS = input.normalWS.xyz;
#endif
inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS);
inputData.viewDirectionWS = viewDirWS;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
inputData.shadowCoord = input.shadowCoord;
#elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
#ifdef _ADDITIONAL_LIGHTS_VERTEX
inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x);
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
#else
inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactor);
#endif
#if defined(DYNAMICLIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV, input.vertexSH, inputData.normalWS);
#elif defined(LIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.vertexSH, inputData.normalWS);
#else
inputData.bakedGI = SampleSH(inputData.normalWS);
#endif
// 仅在运行时全局环境光开启后才覆盖(Game.cs 设置);否则保留场景自身 SH/光照贴图,
// 避免编辑器预览比 URP Lit 亮(旧写法无条件覆盖成硬编码的高强度三色环境光)
if (_XRuntimeAmbientEnabled > 0.5h)
inputData.bakedGI = SampleXRuntimeAmbient(inputData.normalWS);
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#if defined(DEBUG_DISPLAY)
#if defined(DYNAMICLIGHTMAP_ON)
inputData.dynamicLightmapUV = input.dynamicLightmapUV;
#endif
#if defined(LIGHTMAP_ON)
inputData.staticLightmapUV = input.staticLightmapUV;
#else
inputData.vertexSH = input.vertexSH;
#endif
#endif
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 3538332e45c8b1a4f9d4964380ddc6a9
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,322 @@
Shader "Test/XTex"
{
Properties
{
[MainColor] _BaseColor("Color", Color) = (1,1,1,1)
[MainTexture] _MainTex("Albedo", 2D) = "white" {}
[Toggle(_MIXTEX_ON)] _UseMixTex("Use Mix Map", Float) = 0
[MixTexture] _MixTex("MixTex", 2D) = "white" {}
_BumpScale("BumpScale", Range(0.0, 10)) = 5
_Roughness("Roughness", Range(0.0, 2.0)) = 0.4
_Metallic("Metallic", Range(0.0, 2.0)) = 0.3
_AO("AO", Range(0.0, 3.0)) = 1.0
_EmissiveIntensity("EmissiveIntensity", Range(0.0, 2.0)) = 0.3
}
SubShader
{
// Universal Pipeline tag is required. If Universal render pipeline is not set in the graphics settings
// this Subshader will fail. One can add a subshader below or fallback to Standard built-in to make this
// material work with both Universal Render Pipeline and Builtin Unity Pipeline
Tags{ "RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "IgnoreProjector" = "True" }
Pass
{
// Lightmode matches the ShaderPassName set in UniversalRenderPipeline.cs. SRPDefaultUnlit and passes with
// no LightMode tag are also rendered by Universal Render Pipeline
Name "ForwardLit"
Tags{ "LightMode" = "UniversalForward" }
ZWrite on
HLSLPROGRAM
// Required to compile gles 2.0 with standard SRP library
// All shaders must be compiled with HLSLcc and currently only gles is not using HLSLcc by default
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN
#pragma multi_compile _ _ADDITIONAL_LIGHTS_VERTEX _ADDITIONAL_LIGHTS
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DYNAMICLIGHTMAP_ON
#pragma multi_compile _ _MIXTEX_ON
#pragma multi_compile_fragment _ _ADDITIONAL_LIGHT_SHADOWS
#pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH
#pragma vertex vert
#pragma fragment frag
#include "XTex_Base.hlsl"
struct AttData
{
float3 normal;
float ao;//获得夹角越狭窄越强
float roughness;//周围高度差越多,越粗糙;颜色越相同越低;
float metallic;//使用平均亮度值
};
Varyings vert(Attributes input)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
// normalWS and tangentWS already normalize.
// this is required to avoid skewing the direction during interpolation
// also required for per-vertex lighting and SH evaluation
VertexNormalInputs normalInput = GetVertexNormalInputs(input.normalOS, input.tangentOS);
half3 vertexLight = VertexLighting(vertexInput.positionWS, normalInput.normalWS);
half fogFactor = 0;
#if !defined(_FOG_FRAGMENT)
fogFactor = ComputeFogFactor(vertexInput.positionCS.z);
#endif
// already normalized from normal transform to WS.
// half3 viewDirWS = GetWorldSpaceNormalizeViewDir(vertexInput.positionWS);
// output.normalWS = half4(normalInput.normalWS, viewDirWS.x);//normalInput.normalWS;//
//#if defined(REQUIRES_WORLD_SPACE_TANGENT_INTERPOLATOR) || defined(REQUIRES_TANGENT_SPACE_VIEW_DIR_INTERPOLATOR)
// real sign = input.tangentOS.w * GetOddNegativeScale();
// half4 tangentWS = half4(normalInput.tangentWS.xyz, sign);
//#endif
//#if defined(REQUIRES_WORLD_SPACE_TANGENT_INTERPOLATOR)
// output.tangentWS = tangentWS;
//#endif
half3 viewDirWS = GetCameraPositionWS() - vertexInput.positionWS;
output.normalWS = half4(normalInput.normalWS, viewDirWS.x);
output.tangentWS = half4(normalInput.tangentWS, viewDirWS.y);
output.bitangentWS = half4(normalInput.bitangentWS, viewDirWS.z);
#if defined(REQUIRES_TANGENT_SPACE_VIEW_DIR_INTERPOLATOR)
half3 viewDirTS = GetViewDirectionTangentSpace(tangentWS, output.normalWS, viewDirWS);
output.viewDirTS = viewDirTS;
#endif
OUTPUT_LIGHTMAP_UV(input.staticLightmapUV, unity_LightmapST, output.staticLightmapUV);
#ifdef DYNAMICLIGHTMAP_ON
output.dynamicLightmapUV = input.dynamicLightmapUV.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
#endif
OUTPUT_SH(output.normalWS.xyz, output.vertexSH);
#ifdef _ADDITIONAL_LIGHTS_VERTEX
output.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
#else
output.fogFactor = fogFactor;
#endif
output.positionWS = vertexInput.positionWS;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
output.shadowCoord = GetShadowCoord(vertexInput);
#endif
output.positionCS = vertexInput.positionCS;
output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
return output;
}
//生成灰度图(高度)
float GetGrayColor(half3 color)
{
//return color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;
//return color.r * 0.3 + color.g * 0.59 + color.b * 0.11;
return 0.299f * color.r + 0.587f * color.g + 0.114f * color.b;
}
//生成法线 ao 粗糙度,金属度
AttData GetNormalByGray(float2 uv, half4 col4)
{
AttData ad;
half bumpscale = _BumpScale * _MainTex_TexelSize.x;
float2 deltaU = float2(_MainTex_TexelSize.x, 0);
float h0 = GetGrayColor(col4.xyz);
float h1_u = GetGrayColor(SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv - deltaU).rgb);
float h2_u = GetGrayColor(SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv + deltaU).rgb);
//float3 tangent_u = float3(deltaU.x, 0, (h2_u - h0) * bumpscale);
float3 tangent_u = float3(deltaU.x, 0, (h2_u - h1_u) * bumpscale);
float2 deltaV = float2(0, _MainTex_TexelSize.y);
float h1_v = GetGrayColor(SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv - deltaV).rgb);
float h2_v = GetGrayColor(SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, uv + deltaV).rgb);
//float3 tangent_v = float3(0, deltaV.y, (h2_v - h0) * bumpscale);
float3 tangent_v = float3(0, deltaV.y, (h2_v - h1_v) * bumpscale);
//算ao. 两个向量夹角《
float ao;// = 0;
//ad.ao = 0;
ad.normal = normalize(cross(tangent_v, tangent_u));
ad.normal.z *= -1;
float3 vVA = float3(0, deltaV.y, (h2_v - h0) * bumpscale);
float3 vVB = float3(0, deltaV.y, (h1_v - h0) * bumpscale);
float3 VecV = cross(vVA, vVB);
//if (VecV.y > 0)
{//锐角,判断根据锐角度得到夹角深度
ao = saturate(acos(dot(normalize(vVA), normalize(vVB))));
}
float3 vUA = float3(deltaU.x, 0, (h2_u - h0) * bumpscale);
float3 vUB = float3(deltaU.x, 0, (h1_u - h0) * bumpscale);
float3 VecU = cross(vUA, vUB);
//if (VecU.y > 0)
{//锐角,判断根据锐角度得到夹角深度
ad.ao = saturate(acos(dot(normalize(vUA), normalize(vUB))));
}
ad.ao = saturate(1.0f - max(ao, ad.ao) * _AO);
//
//粗糙度
ad.roughness = saturate((abs(h1_u - h0) + abs(h2_u - h0) + abs(h1_v - h0) + abs(h2_v - h0)) + _Roughness);
//金属度
ad.metallic = saturate((h0 + h1_u + h2_u + h1_v + h2_v) / 5 * _Metallic);
return ad;
}
half4 frag(Varyings input) : SV_Target
{
UNITY_SETUP_INSTANCE_ID(input);
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
#if defined(_PARALLAXMAP)
#if defined(REQUIRES_TANGENT_SPACE_VIEW_DIR_INTERPOLATOR)
half3 viewDirTS = input.viewDirTS;
#else
half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
half3 viewDirTS = GetViewDirectionTangentSpace(input.tangentWS, input.normalWS, viewDirWS);
#endif
ApplyPerPixelDisplacement(viewDirTS, input.uv);
#endif
SurfaceData surfaceData;
//InitializeStandardLitSurfaceData(input.uv, surfaceData);
half4 albedoAlpha = SampleAlbedoAlpha(input.uv, TEXTURE2D_ARGS(_MainTex, sampler_MainTex));
half3 albedo = albedoAlpha.rgb * _BaseColor.rgb;
//Light mainLight = GetMainLight();
#ifdef _MIXTEX_ON
half4 mixTex = SAMPLE_TEXTURE2D(_MixTex, sampler_MixTex, input.uv);
AttData ad;// = GetNormalByGray(input.uv, albedoAlpha);;
ad.normal.rgb = DecodeSphereMap(mixTex.rg);
ad.ao = saturate(1.0 - (1.0 - mixTex.a) * _AO);
ad.roughness = mixTex.a * _Roughness;
ad.metallic = mixTex.b * _Metallic;
#else
//得到法线
AttData ad = GetNormalByGray(input.uv, albedoAlpha);
//half gray = GetGrayColor(albedoAlpha.xyz);
//ad.normal.rgb = half3(gray,gray,gray);
#endif
//half3 viewDirWS = half3(input.normalWS.w, input.tangentWS.w, input.bitangentWS.w);
half3 normalWS = TransformTangentToWorld(ad.normal,
half3x3(input.tangentWS.xyz, input.bitangentWS.xyz, input.normalWS.xyz));
surfaceData.specular = half3(0.0, 0.0, 0.0);
surfaceData.albedo = albedo;
surfaceData.metallic = ad.metallic;
surfaceData.smoothness = 1.0 - ad.roughness; // 新版URP中smoothness直接控制高光
surfaceData.alpha = albedoAlpha.a;
surfaceData.normalTS = ad.normal;//input.tangentWS;//
//surfaceData.specular = 0;
surfaceData.emission = half3(0.0, 0.0, 0.0);
surfaceData.occlusion = ad.ao;
surfaceData.clearCoatMask = half(0.0);
surfaceData.clearCoatSmoothness = half(0.0);
InputData inputData;
input.normalWS.rgb = normalWS;//ad.normal;//法线需要传入
InitializeInputData(input, surfaceData.normalTS, inputData);
//SETUP_DEBUG_TEXTURE_DATA(inputData, input.uv, _BaseMap);
//#ifdef _DBUFFER
// ApplyDecalToSurfaceData(input.positionCS, surfaceData, inputData);
//#endif
half4 color = UniversalFragmentPBR(inputData, surfaceData);
color.rgb = MixFog(color.rgb, inputData.fogCoord);
//color.a = OutputAlpha(color.a, _Surface);
//color.rgb = input.tangentWS;//normalWS;//surfaceData.normalTS;//
return color;
}
ENDHLSL
}
Pass
{
Name "ShadowCaster"
Tags{ "LightMode" = "ShadowCaster" }
ZWrite On
ZTest LEqual
Cull[_Cull]
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma exclude_renderers d3d11_9x
#pragma target 2.0
// -------------------------------------
// Material Keywords
#pragma shader_feature_local_fragment _ALPHATEST_ON
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#include "XTex_Base.hlsl"
Varyings vert(Attributes input)
{
Varyings output = (Varyings)0;
UNITY_SETUP_INSTANCE_ID(input);
UNITY_TRANSFER_INSTANCE_ID(input, output);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
float3 positionWS = TransformObjectToWorld(input.positionOS.xyz);
float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
float4 positionCS = TransformWorldToHClip(positionWS);
#if UNITY_REVERSED_Z
positionCS.z = min(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
#else
positionCS.z = max(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
#endif
output.positionCS = positionCS;
output.uv = TRANSFORM_TEX(input.texcoord, _MainTex);
return output;
}
half4 frag(Varyings input) : SV_TARGET
{
return SampleAlbedoAlpha(input.uv, TEXTURE2D_ARGS(_BaseMap, sampler_BaseMap)).a;
//return 0;
}
ENDHLSL
}
//UsePass "Universal Render Pipeline/Lit/ShadowCaster"
}
FallBack Off
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 32be331071e4bc34895b26703115c3e6
ShaderImporter:
externalObjects: {}
defaultTextures:
- _MainTex: {instanceID: 0}
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,172 @@
#ifndef XTEX_LIT_BASE
#define XTEX_LIT_BASE
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/SurfaceInput.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
CBUFFER_START(UnityPerMaterial)
float4 _MainTex_ST;
half4 _BaseColor;
half _BumpScale;
half _Roughness;
half _Metallic;
half _AO;
half _EmissiveIntensity;
half _useCustomGI;
half3 _CustomGIColor;
float4 _MainTex_TexelSize;
#ifdef _MIXTEX_ON
float4 _MixTex_ST;
#endif
CBUFFER_END
half _XRuntimeAmbientEnabled;
half4 _XRuntimeAmbientSky;
half4 _XRuntimeAmbientEquator;
half4 _XRuntimeAmbientGround;
TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);
#ifdef _MIXTEX_ON
TEXTURE2D(_MixTex); SAMPLER(sampler_MixTex);
#endif
struct Attributes
{
float4 positionOS : POSITION;
half4 color : COLOR;
float3 normalOS : NORMAL;
float4 tangentOS : TANGENT;
float2 texcoord : TEXCOORD0;
float2 staticLightmapUV : TEXCOORD1;
#ifdef DYNAMICLIGHTMAP_ON
float2 dynamicLightmapUV : TEXCOORD2;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct Varyings
{
float2 uv : TEXCOORD0;
DECLARE_LIGHTMAP_OR_SH(staticLightmapUV, vertexSH, 1);
float3 positionWS : TEXCOORD2;
half4 normalWS : TEXCOORD3; // xyz: normal, w: viewDir.x
half4 tangentWS : TEXCOORD4; // xyz: tangent, w: viewDir.y
half4 bitangentWS : TEXCOORD5; // xyz: bitangent, w: viewDir.z
#ifdef _ADDITIONAL_LIGHTS_VERTEX
half4 fogFactorAndVertexLight : TEXCOORD6; // x: fogFactor, yzw: vertex light
#else
half fogFactor : TEXCOORD6;
#endif
half4 lightDir : TEXCOORD8;
half4 viewDir : TEXCOORD9;
#ifdef DYNAMICLIGHTMAP_ON
float2 dynamicLightmapUV : TEXCOORD7;
#endif
float4 positionCS : SV_POSITION;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
float4 shadowCoord : TEXCOORD10;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
real3 SafeNormalize_Half3(real3 inVec)
{
real dp3 = max(REAL_MIN, dot(inVec, inVec));
return inVec * rsqrt(dp3);
}
float3 DecodeSphereMap(float2 encoded)
{
float4 nn = float4(encoded, 1, -1);
float l = dot(nn.xyz, -nn.xyw);
nn.z = l;
nn.xy *= sqrt(l);
return nn.xyz * 2 + float3(0, 0, -1);
}
half3 SampleXRuntimeAmbient(half3 normalWS)
{
half y = normalize(normalWS).y;
half useGlobal = step(0.5h, _XRuntimeAmbientEnabled);
half3 sky = lerp(half3(1.353h, 1.452h, 1.568h), _XRuntimeAmbientSky.rgb, useGlobal);
half3 equator = lerp(half3(1.023h, 1.122h, 1.254h), _XRuntimeAmbientEquator.rgb, useGlobal);
half3 ground = lerp(half3(0.561h, 0.528h, 0.462h), _XRuntimeAmbientGround.rgb, useGlobal);
half3 upper = lerp(equator, sky, saturate(y));
half3 lower = lerp(equator, ground, saturate(-y));
return lerp(lower, upper, step(0.0h, y));
}
void InitializeInputData(Varyings input, half3 normalTS, out InputData inputData)
{
inputData = (InputData)0;
inputData.positionWS = input.positionWS;
half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
#if defined(_NORMALMAP) || defined(_DETAIL)
float sgn = input.tangentWS.w; // should be either +1 or -1
float3 bitangent = sgn * cross(input.normalWS.xyz, input.tangentWS.xyz);
half3x3 tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, input.normalWS.xyz);
#if defined(_NORMALMAP)
inputData.tangentToWorld = tangentToWorld;
#endif
inputData.normalWS = TransformTangentToWorld(normalTS, tangentToWorld);
#else
inputData.normalWS = input.normalWS.xyz;
#endif
inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS);
inputData.viewDirectionWS = viewDirWS;
#if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
inputData.shadowCoord = input.shadowCoord;
#elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
#ifdef _ADDITIONAL_LIGHTS_VERTEX
inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x);
inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
#else
inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactor);
#endif
#if defined(DYNAMICLIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV, input.vertexSH, inputData.normalWS);
#elif defined(LIGHTMAP_ON)
inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.vertexSH, inputData.normalWS);
#else
inputData.bakedGI = SampleSH(inputData.normalWS);
#endif
// 仅在运行时全局环境光开启后才覆盖(Game.cs 设置);否则保留场景自身 SH/光照贴图,
// 避免编辑器预览比 URP Lit 亮(旧写法无条件覆盖成硬编码的高强度三色环境光)
if (_XRuntimeAmbientEnabled > 0.5h)
inputData.bakedGI = SampleXRuntimeAmbient(inputData.normalWS);
inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
#if defined(DEBUG_DISPLAY)
#if defined(DYNAMICLIGHTMAP_ON)
inputData.dynamicLightmapUV = input.dynamicLightmapUV;
#endif
#if defined(LIGHTMAP_ON)
inputData.staticLightmapUV = input.staticLightmapUV;
#else
inputData.vertexSH = input.vertexSH;
#endif
#endif
}
#endif
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: a68f172b57b5e5e4f8842cd5a63f22a3
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because one or more lines are too long
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 297292b243665ee45b0e0f266b016347
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,296 @@
#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using YooAsset.Editor;
/// <summary>
/// M3:角色目录约定 Assets/Bundles/Characters/{ActorName}/ + Art 包收集。
/// </summary>
public static class SetupM3Character
{
public const string ActorName = "MaleExplorer";
public const string ActorRoot = "Assets/Bundles/Characters/" + ActorName;
const string FbxPath = ActorRoot + "/" + ActorName + ".fbx";
const string BasePath = ActorRoot + "/" + ActorName + "_base.png";
const string MixPath = ActorRoot + "/" + ActorName + "_mix.png";
const string ColorPath = ActorRoot + "/" + ActorName + "_color.png";
const string NormalPath = ActorRoot + "/" + ActorName + "_normal.png";
const string AoPath = ActorRoot + "/" + ActorName + "_ao.png";
const string MetallicPath = ActorRoot + "/" + ActorName + "_metallic.png";
const string RoughnessPath = ActorRoot + "/" + ActorName + "_roughness.png";
const string ConceptPath = ActorRoot + "/concept.png";
const string MatPath = ActorRoot + "/" + ActorName + ".mat";
const string PrefabPath = ActorRoot + "/" + ActorName + ".prefab";
const string ArtPackage = "Art";
const string XPbrShaderName = "Test/XPbr";
[MenuItem("AIGame/M3/Setup Character Prefab + Art Collector")]
public static string SetupAll()
{
AssetDatabase.Refresh();
var a = EnsureTextureImports();
var b = EnsureMaterialAndPrefab();
var c = EnsureArtCollector();
CleanupLegacyLayout();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
return $"ok textures={a} prefab={b} art={c}";
}
public static string EnsureTextureImports()
{
var paths = new[] { BasePath, MixPath, ColorPath, NormalPath, AoPath, MetallicPath, RoughnessPath, ConceptPath };
var ok = 0;
foreach (var path in paths)
{
if (!File.Exists(path)) continue;
var importer = AssetImporter.GetAtPath(path) as TextureImporter;
if (importer == null) continue;
var isMix = path == MixPath;
var isNormal = path == NormalPath;
var isData = path == MetallicPath || path == RoughnessPath || path == AoPath || isMix;
importer.textureType = isNormal ? TextureImporterType.NormalMap : TextureImporterType.Default;
importer.sRGBTexture = !isNormal && !isData;
importer.mipmapEnabled = true;
importer.alphaIsTransparency = path == ConceptPath || path == BasePath;
importer.SaveAndReimport();
ok++;
}
if (File.Exists(FbxPath))
{
var model = AssetImporter.GetAtPath(FbxPath) as ModelImporter;
if (model != null)
{
// XPbr:保留 externalObjects 材质重映射;无 .mat 时再 None
model.materialImportMode = File.Exists(MatPath)
? ModelImporterMaterialImportMode.ImportViaMaterialDescription
: ModelImporterMaterialImportMode.None;
model.meshCompression = ModelImporterMeshCompression.Medium;
model.isReadable = false;
model.SaveAndReimport();
}
}
return $"imported={ok} fbx={(File.Exists(FbxPath) ? "yes" : "no")}";
}
public static string EnsureMaterialAndPrefab()
{
if (File.Exists(FbxPath) && (File.Exists(BasePath) || File.Exists(ColorPath)))
return EnsureMeshPrefab();
if (File.Exists(ConceptPath))
return EnsureBillboardPrefab();
return "missing MaleExplorer mesh/concept under " + ActorRoot;
}
static string EnsureMeshPrefab()
{
var baseMap = AssetDatabase.LoadAssetAtPath<Texture2D>(BasePath);
var mixMap = AssetDatabase.LoadAssetAtPath<Texture2D>(MixPath);
var color = baseMap != null ? baseMap : AssetDatabase.LoadAssetAtPath<Texture2D>(ColorPath);
if (color == null) return "base/color texture missing";
var xpbr = Shader.Find(XPbrShaderName);
var urpLit = Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard");
var useXpbr = xpbr != null && mixMap != null;
var shader = useXpbr ? xpbr : urpLit;
var mat = AssetDatabase.LoadAssetAtPath<Material>(MatPath);
if (mat == null)
{
mat = new Material(shader);
AssetDatabase.CreateAsset(mat, MatPath);
}
else
{
mat.shader = shader;
}
if (useXpbr)
{
if (mat.HasProperty("_MainTex")) mat.SetTexture("_MainTex", color);
if (mat.HasProperty("_MixTex")) mat.SetTexture("_MixTex", mixMap);
if (mat.HasProperty("_BaseColor")) mat.SetColor("_BaseColor", Color.white);
if (mat.HasProperty("_Metallic")) mat.SetFloat("_Metallic", 1f);
if (mat.HasProperty("_Roughness")) mat.SetFloat("_Roughness", 1f);
if (mat.HasProperty("_AO")) mat.SetFloat("_AO", 1f);
if (mat.HasProperty("_AlphaTest")) mat.SetFloat("_AlphaTest", 0f);
mat.DisableKeyword("_ALPHATEST_ON");
}
else
{
var normal = AssetDatabase.LoadAssetAtPath<Texture2D>(NormalPath);
var ao = AssetDatabase.LoadAssetAtPath<Texture2D>(AoPath);
var metallic = AssetDatabase.LoadAssetAtPath<Texture2D>(MetallicPath);
var roughness = AssetDatabase.LoadAssetAtPath<Texture2D>(RoughnessPath);
if (mat.HasProperty("_BaseMap")) mat.SetTexture("_BaseMap", color);
if (mat.HasProperty("_MainTex")) mat.SetTexture("_MainTex", color);
if (mat.HasProperty("_BumpMap") && normal != null)
{
mat.SetTexture("_BumpMap", normal);
mat.EnableKeyword("_NORMALMAP");
}
if (mat.HasProperty("_OcclusionMap") && ao != null)
mat.SetTexture("_OcclusionMap", ao);
if (mat.HasProperty("_MetallicGlossMap") && metallic != null)
{
mat.SetTexture("_MetallicGlossMap", metallic);
mat.EnableKeyword("_METALLICSPECGLOSSMAP");
}
if (mat.HasProperty("_Smoothness") && roughness != null)
mat.SetFloat("_Smoothness", 0.45f);
if (mat.HasProperty("_BaseColor")) mat.SetColor("_BaseColor", Color.white);
}
EditorUtility.SetDirty(mat);
var modelRoot = AssetDatabase.LoadAssetAtPath<GameObject>(FbxPath);
if (modelRoot == null) return "fbx not loaded";
var instance = (GameObject)PrefabUtility.InstantiatePrefab(modelRoot);
instance.name = ActorName;
foreach (var renderer in instance.GetComponentsInChildren<Renderer>())
renderer.sharedMaterial = mat;
// 落地参考盘
var ground = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
ground.name = "ShadowDisc";
ground.transform.SetParent(instance.transform, false);
ground.transform.localPosition = new Vector3(0f, 0.02f, 0f);
ground.transform.localScale = new Vector3(0.7f, 0.015f, 0.7f);
Object.DestroyImmediate(ground.GetComponent<Collider>());
var gMat = new Material(urpLit != null ? urpLit : shader);
if (gMat.HasProperty("_BaseColor")) gMat.SetColor("_BaseColor", new Color(0.12f, 0.12f, 0.14f, 1f));
if (gMat.HasProperty("_Color")) gMat.color = new Color(0.12f, 0.12f, 0.14f, 1f);
ground.GetComponent<MeshRenderer>().sharedMaterial = gMat;
ground.GetComponent<MeshRenderer>().shadowCastingMode = ShadowCastingMode.Off;
// 粗略归一化身高约 1.8m
var bounds = new Bounds(instance.transform.position, Vector3.zero);
var renderers = instance.GetComponentsInChildren<Renderer>();
foreach (var r in renderers)
{
if (r.name == "ShadowDisc") continue;
bounds.Encapsulate(r.bounds);
}
if (bounds.size.y > 0.01f)
{
var scale = 1.8f / bounds.size.y;
instance.transform.localScale = Vector3.one * scale;
}
PrefabUtility.SaveAsPrefabAsset(instance, PrefabPath);
Object.DestroyImmediate(instance);
return PrefabPath;
}
static string EnsureBillboardPrefab()
{
var tex = AssetDatabase.LoadAssetAtPath<Texture2D>(ConceptPath);
if (tex == null) return "concept not loaded";
var shader = Shader.Find("Universal Render Pipeline/Unlit");
if (shader == null) shader = Shader.Find("Unlit/Transparent");
if (shader == null) shader = Shader.Find("Sprites/Default");
var mat = AssetDatabase.LoadAssetAtPath<Material>(MatPath);
if (mat == null)
{
mat = new Material(shader);
AssetDatabase.CreateAsset(mat, MatPath);
}
else mat.shader = shader;
if (mat.HasProperty("_BaseMap")) mat.SetTexture("_BaseMap", tex);
if (mat.HasProperty("_MainTex")) mat.SetTexture("_MainTex", tex);
if (mat.HasProperty("_BaseColor")) mat.SetColor("_BaseColor", Color.white);
if (mat.HasProperty("_Surface")) mat.SetFloat("_Surface", 1f);
mat.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
mat.renderQueue = (int)RenderQueue.Transparent;
EditorUtility.SetDirty(mat);
var root = new GameObject(ActorName);
root.transform.localScale = new Vector3(1.2f, 2.0f, 1f);
var quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
quad.name = "Billboard";
quad.transform.SetParent(root.transform, false);
quad.transform.localPosition = new Vector3(0f, 1.0f, 0f);
Object.DestroyImmediate(quad.GetComponent<MeshCollider>());
quad.GetComponent<MeshRenderer>().sharedMaterial = mat;
PrefabUtility.SaveAsPrefabAsset(root, PrefabPath);
Object.DestroyImmediate(root);
return PrefabPath + " (billboard fallback)";
}
static void CleanupLegacyLayout()
{
// 旧 M3 扁平目录,迁移后删除空壳
var legacy = new[]
{
"Assets/Bundles/Characters/Prefabs/MaleExplorer.prefab",
"Assets/Bundles/Characters/Textures/male_explorer.png",
"Assets/Bundles/Characters/Textures/MaleExplorer_Billboard.mat",
};
foreach (var path in legacy)
{
if (File.Exists(path) || AssetDatabase.LoadMainAssetAtPath(path) != null)
AssetDatabase.DeleteAsset(path);
}
}
public static string EnsureArtCollector()
{
var setting = BundleCollectorSettingData.Setting;
setting.ShowPackageView = true;
var package = setting.Packages.Find(p => p.PackageName == ArtPackage);
if (package == null)
package = BundleCollectorSettingData.CreatePackage(ArtPackage);
package.PackageDesc = "角色/场景美术";
package.EnableAddressable = true;
package.SupportExtensionless = true;
package.AutoCollectShaders = true;
package.IgnoreRuleName = nameof(NormalIgnoreRule);
BundleCollectorSettingData.ModifyPackage(package);
var group = package.Groups.Find(g => g.GroupName == "Characters");
if (group == null)
group = BundleCollectorSettingData.CreateGroup(package, "Characters");
group.ActiveRuleName = nameof(EnableGroup);
group.AssetTags = "art";
BundleCollectorSettingData.ModifyGroup(package, group);
const string collectPath = "Assets/Bundles/Characters";
var collector = group.Collectors.Find(c => c.CollectPath == collectPath);
if (collector == null)
{
collector = new BundleCollector
{
CollectPath = collectPath,
CollectorGUID = AssetDatabase.AssetPathToGUID(collectPath),
CollectorType = ECollectorType.MainAssetCollector,
AddressRuleName = nameof(AddressByFileName),
PackRuleName = nameof(PackDirectory),
FilterRuleName = nameof(CollectAll),
AssetTags = "art",
};
BundleCollectorSettingData.CreateCollector(group, collector);
}
else
{
collector.CollectorGUID = AssetDatabase.AssetPathToGUID(collectPath);
collector.AddressRuleName = nameof(AddressByFileName);
collector.PackRuleName = nameof(PackDirectory);
collector.FilterRuleName = nameof(CollectAll);
BundleCollectorSettingData.ModifyCollector(group, collector);
}
package.CheckConfigError();
BundleCollectorSettingData.SaveFile();
return $"package={ArtPackage} collect={collectPath} pack=PackDirectory";
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 15d1983461c3f204ca40fed18bc55a6f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,122 @@
#if UNITY_EDITOR
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using YooAsset;
using YooAsset.Editor;
namespace AOT.Editor.YooAssetTools
{
/// <summary>
/// 构建 Art 包(角色等)并暂存 CDN / StreamingAssets。
/// </summary>
public static class BuildAndStageArt
{
public const string PackageName = "Art";
public const string AppVersion = "1.0.0";
public const string Channel = "wechat";
static string RepoRoot => Path.GetFullPath(Path.Combine(Application.dataPath, "..", ".."));
static string CdnRoot => Path.Combine(RepoRoot, "Tools", "cdn_root");
static string ProjectBundlesRoot => BundleBuilderHelper.GetDefaultBuildOutputRoot();
[MenuItem("AIGame/YooAsset/Build And Stage Art")]
public static string BuildAndStage()
{
SetupM3Character.SetupAll();
var target = EditorUserBuildSettings.activeBuildTarget;
string packageVersion = DateTime.Now.ToString("yyyyMMdd.HHmmss");
var buildResult = BuildArtPackage(target, packageVersion);
if (!buildResult.Success)
return $"fail: {buildResult.ErrorInfo}";
string packageDir = buildResult.OutputPackageDirectory;
string stageDir = Path.Combine(CdnRoot, Channel, AppVersion, PackageName);
StageDirectory(packageDir, stageDir);
// 合并 version.json packages 列表
MergeVersionPackages(packageVersion);
AssetDatabase.Refresh();
return $"ok ver={packageVersion} dir={packageDir} stage={stageDir}";
}
static BuildResult BuildArtPackage(BuildTarget target, string packageVersion)
{
var uniqueBundleName = BundleCollectorSettingData.Setting.UniqueBundleName;
var packRuleResult = DefaultBundlePackRule.CreateShadersPackRuleResult();
var builtinShaderBundleName = packRuleResult.GetBundleName(PackageName, uniqueBundleName);
var buildParameters = new ScriptableBuildParameters
{
BuildOutputRoot = ProjectBundlesRoot,
BundledFileRoot = BundleBuilderHelper.GetStreamingAssetsRoot(),
BuildPipeline = EBuildPipeline.ScriptableBuildPipeline.ToString(),
BuildBundleType = (int)EBundleType.AssetBundle,
BuildTarget = target,
PackageName = PackageName,
PackageVersion = packageVersion,
EnableSharePackRule = true,
VerifyBuildingResult = true,
FileNameStyle = EFileNameStyle.HashName,
BundledCopyOption = EBundledCopyOption.ClearAndCopyAll,
BundledCopyParams = string.Empty,
CompressOption = ECompressOption.LZ4,
ClearBuildCacheFiles = false,
UseAssetDependencyDB = true,
BuiltinShadersBundleName = builtinShaderBundleName,
};
var pipeline = new ScriptableBuildPipeline();
return pipeline.Run(buildParameters, true);
}
static void StageDirectory(string src, string dst)
{
if (Directory.Exists(dst))
Directory.Delete(dst, true);
Directory.CreateDirectory(dst);
foreach (var file in Directory.GetFiles(src, "*", SearchOption.AllDirectories))
{
var rel = file.Substring(src.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var destFile = Path.Combine(dst, rel);
Directory.CreateDirectory(Path.GetDirectoryName(destFile) ?? dst);
File.Copy(file, destFile, true);
}
}
static void MergeVersionPackages(string resVersion)
{
var path = Path.Combine(CdnRoot, Channel, "version.json");
Directory.CreateDirectory(Path.GetDirectoryName(path) ?? CdnRoot);
var localCdn = $"http://127.0.0.1:8787/{Channel}/{AppVersion}/{BuildAndStageHotUpdate.PackageName}";
var json =
"{\n" +
$" \"appVersionMin\": \"{AppVersion}\",\n" +
$" \"appVersionMax\": \"{AppVersion}\",\n" +
$" \"resVersion\": \"{resVersion}\",\n" +
$" \"cdnRoot\": \"{localCdn}\",\n" +
" \"packages\": [ \"DefaultPackage\", \"Art\" ],\n" +
" \"forceUpdate\": false,\n" +
" \"notice\": \"\"\n" +
"}\n";
File.WriteAllText(path, json);
File.WriteAllText(Path.Combine(Application.streamingAssetsPath, "cdn", "version.json"), json);
var prod =
"{\n" +
$" \"appVersionMin\": \"{AppVersion}\",\n" +
$" \"appVersionMax\": \"{AppVersion}\",\n" +
$" \"resVersion\": \"{resVersion}\",\n" +
$" \"cdnRoot\": \"https://www.xworld.ren/{Channel}/{AppVersion}/{BuildAndStageHotUpdate.PackageName}\",\n" +
" \"packages\": [ \"DefaultPackage\", \"Art\" ],\n" +
" \"forceUpdate\": false,\n" +
" \"notice\": \"\"\n" +
"}\n";
File.WriteAllText(Path.Combine(CdnRoot, Channel, "version.prod.json"), prod);
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: db0c7c0cdfa612f47bea89cc1bd02a6e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -3,13 +3,12 @@ using AOT.Boot;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;
using YooAsset;
namespace AOT.Editor.YooAssetTools
{
/// <summary>
/// 切换 BootDriver 的 M1 验证模式(Offline / Host / Direct)。
/// 切换 BootDriver 的运行模式 / 服务器地址。
/// </summary>
public static class ConfigureBootPlayMode
{
@@ -30,6 +29,33 @@ namespace AOT.Editor.YooAssetTools
versionUrl: "http://127.0.0.1:8787/wechat/version.json",
defaultCdn: "http://127.0.0.1:8787/wechat/1.0.0/DefaultPackage");
[MenuItem("AIGame/Boot/Server/Production game.xworld.ren")]
public static string SetServerProd() => ApplyServer(
"https://game.xworld.ren",
"wss://game.xworld.ren/ws?pid={pid}&token={token}");
[MenuItem("AIGame/Boot/Server/Local AIServer :8080")]
public static string SetServerLocal() => ApplyServer(
"http://127.0.0.1:8080",
"ws://127.0.0.1:8080/ws?pid={pid}&token={token}");
static string ApplyServer(string httpBase, string wsTemplate)
{
var scene = EditorSceneManager.OpenScene(BootScene, OpenSceneMode.Single);
var boot = Object.FindObjectOfType<BootDriver>();
if (boot == null)
return "fail: BootDriver not found in Boot scene";
var so = new SerializedObject(boot);
var settings = so.FindProperty("settings");
settings.FindPropertyRelative("HttpBase").stringValue = httpBase;
settings.FindPropertyRelative("WsUrlTemplate").stringValue = wsTemplate;
so.ApplyModifiedPropertiesWithoutUndo();
EditorSceneManager.MarkSceneDirty(scene);
EditorSceneManager.SaveScene(scene);
return $"ok http={httpBase} ws={wsTemplate}";
}
static string Apply(EPlayMode playMode, bool editorDirect, string versionUrl = null, string defaultCdn = null)
{
var scene = EditorSceneManager.OpenScene(BootScene, OpenSceneMode.Single);
@@ -0,0 +1,98 @@
using System.Collections;
using AOT.Boot;
using UnityEngine;
using YooAsset;
namespace HotUpdate
{
/// <summary>
/// M3:加载示例角色 MaleExplorer 进场景。
/// </summary>
public sealed class CharacterSpawner : MonoBehaviour
{
public const string PrefabAddress = "MaleExplorer";
public const string EditorPrefabPath = "Assets/Bundles/Characters/MaleExplorer/MaleExplorer.prefab";
public const string ArtPackageName = "Art";
BootContext _ctx;
GameObject _instance;
public void Bind(BootContext ctx) => _ctx = ctx;
public void Spawn()
{
StartCoroutine(SpawnCo());
}
IEnumerator SpawnCo()
{
GameObject prefab = null;
// 1) YooAsset Art 包(Offline/Host 已初始化时)
if (YooAssets.IsInitialized && YooAssets.TryGetPackage(ArtPackageName, out var art) &&
art.InitializeStatus == EOperationStatus.Succeeded)
{
var handle = art.LoadAssetAsync<GameObject>(PrefabAddress);
yield return handle;
if (handle.Status == EOperationStatus.Succeeded)
{
prefab = handle.GetAssetObject<GameObject>();
Debug.Log($"[CharacterSpawner] loaded from YooAsset Art address={PrefabAddress}");
}
else
{
Debug.LogWarning($"[CharacterSpawner] Art load failed: {handle.Error}");
handle.Release();
}
}
// 2) 编辑器直通:AssetDatabase
#if UNITY_EDITOR
if (prefab == null)
{
prefab = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(EditorPrefabPath);
if (prefab != null)
Debug.Log($"[CharacterSpawner] loaded via AssetDatabase {EditorPrefabPath}");
}
#endif
if (prefab == null)
{
Debug.LogError("[CharacterSpawner] MaleExplorer prefab not found");
yield break;
}
if (_instance != null)
Destroy(_instance);
_instance = Instantiate(prefab);
_instance.name = "MaleExplorer_Runtime";
_instance.transform.position = new Vector3(0f, 0f, 2.5f);
DontDestroyOnLoad(_instance);
// 简易朝向相机
var billboard = _instance.GetComponentInChildren<MeshRenderer>();
if (billboard != null && Camera.main != null)
{
var t = billboard.transform;
var cam = Camera.main.transform;
var dir = cam.position - t.position;
dir.y = 0f;
if (dir.sqrMagnitude > 0.001f)
t.rotation = Quaternion.LookRotation(-dir.normalized);
}
// 调整主相机看向角色(竖屏)
if (Camera.main != null)
{
var cam = Camera.main;
cam.transform.position = new Vector3(0f, 1.4f, -1.2f);
cam.transform.rotation = Quaternion.Euler(8f, 0f, 0f);
cam.fieldOfView = 50f;
cam.backgroundColor = new Color(0.45f, 0.62f, 0.78f);
}
Debug.Log($"[CharacterSpawner] spawned ok res={_ctx?.ResVersion}");
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9cd65ba42ca5feb4b9912b12d3edb8c0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+6 -1
View File
@@ -36,6 +36,11 @@ namespace HotUpdate
Debug.Log($"[HotUpdate] Bootstrap ready. CDN={_ctx?.CdnRoot}");
EnsureHud();
// M3:示例角色(与网络并行,不依赖 WS)
var spawner = gameObject.AddComponent<CharacterSpawner>();
spawner.Bind(_ctx);
spawner.Spawn();
_net = gameObject.AddComponent<GameNet>();
_net.Bind(_ctx);
_net.OnStatus += s =>
@@ -45,7 +50,7 @@ namespace HotUpdate
_net.OnWsReady += () =>
{
if (_hud != null)
_hud.text = $"WS OK pid={_net.Session?.Pid}";
_hud.text = $"WS OK pid={_net.Session?.Pid} | MaleExplorer";
Debug.Log($"[HotUpdate] M2 WS ready pid={_net.Session?.Pid}");
};
_net.StartGuestSession();
@@ -28,7 +28,12 @@ namespace HotUpdate.Net
public void Bind(BootContext boot)
{
_boot = boot;
if (_boot != null && !string.IsNullOrEmpty(_boot.WsUrlTemplate))
if (_boot == null) return;
if (!string.IsNullOrEmpty(_boot.HttpBase))
HttpBase = _boot.HttpBase;
if (!string.IsNullOrEmpty(_boot.WsUrlTemplate))
{
// 旧模板只有 pid 时补上 token
var tpl = _boot.WsUrlTemplate;
+2 -1
View File
@@ -275,7 +275,8 @@ MonoBehaviour:
DefaultCdnRoot: https://www.xworld.ren/wechat/1.0.0/DefaultPackage
PackageName: DefaultPackage
HotUpdateDllLocation: HotUpdate.Runtime
WsUrlTemplate: wss://game.xworld.ren/ws?pid={pid}
HttpBase: http://127.0.0.1:8080
WsUrlTemplate: ws://127.0.0.1:8080/ws?pid={pid}&token={token}
PlayMode: 1
EditorDirectHotUpdate: 1
AllowStreamingVersionFallback: 1
+8
View File
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c052dd71adfbe4c43883cfe3890c27ff
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +1,9 @@
{
"appVersionMin": "1.0.0",
"appVersionMax": "1.0.0",
"resVersion": "20260921.151412",
"resVersion": "20260921.162205",
"cdnRoot": "http://127.0.0.1:8787/wechat/1.0.0/DefaultPackage",
"packages": [ "DefaultPackage" ],
"packages": [ "DefaultPackage", "Art" ],
"forceUpdate": false,
"notice": ""
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dfd46eb5439d69f40a326819e7449a7d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c006fc95ab2e2a94ab932f4e780a471d
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 8b08706117575b1448b97dad966618dd
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1 @@
20260921.162205
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 9a79c8ae414118b43a0c61bf97427726
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c07a3598c9b7a4b48bdbfaf207b102d5
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1 @@
27be2f3e
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 4c20c4c67eee17441a2340c261467bb6
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 37cda0a6146d51a40be3a2106a5ad9e0
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,19 @@
{
"FileVersion": 1,
"PackageName": "Art",
"PackageVersion": "20260921.162205",
"Entries": [
{
"BundleGuid": "42dd6fb16989293c17dee4df4385c69a",
"FileName": "42dd6fb16989293c17dee4df4385c69a.bundle"
},
{
"BundleGuid": "5df3e28299f252104333a42f18c79ede",
"FileName": "5df3e28299f252104333a42f18c79ede.bundle"
},
{
"BundleGuid": "ec4f2a79e05292f37c2a9ca0f699a992",
"FileName": "ec4f2a79e05292f37c2a9ca0f699a992.bundle"
}
]
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 6ff0ff5f5f23b20468908b333794042d
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c3b303465611475448173599de5dae1a
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
+42
View File
@@ -0,0 +1,42 @@
cmake_minimum_required(VERSION 3.20)
project(AIServer LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(aiserver
src/main.cpp
src/db.cpp
src/auth.cpp
src/http_ws_server.cpp
src/crypto.cpp
third_party/sqlite3.c
)
target_include_directories(aiserver PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_CURRENT_SOURCE_DIR}/third_party
)
# SQLite: 关闭部分扩展,加快编译
target_compile_definitions(aiserver PRIVATE
SQLITE_OMIT_LOAD_EXTENSION
SQLITE_THREADSAFE=1
_CRT_SECURE_NO_WARNINGS
)
if(WIN32)
target_link_libraries(aiserver PRIVATE ws2_32 bcrypt)
# sqlite3.c 是 C,MSVC 下关闭部分告警
if(MSVC)
target_compile_options(aiserver PRIVATE /W3 /utf-8)
set_source_files_properties(third_party/sqlite3.c PROPERTIES COMPILE_FLAGS "/W0")
endif()
else()
target_link_libraries(aiserver PRIVATE pthread dl)
endif()
# 运行时默认数据目录:可执行文件旁的 data/
add_custom_command(TARGET aiserver POST_BUILD
COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:aiserver>/data
)
+43
View File
@@ -0,0 +1,43 @@
# AIServer
C++ 登录 / WebSocket 网关(SQLite),协议兼容客户端 `HotUpdate.Net`。
## 接口
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| POST | `/register` | `{"username","password"}` → `{"token","pid"}` |
| POST | `/login` | 同上 |
| GET | `/health` | 健康检查 |
| WS | `/ws?pid={pid}&token={token}` | 无 token → 401;支持 `hello`/`ping` 应用层应答 |
本地默认:`http://127.0.0.1:8080`、`ws://127.0.0.1:8080/ws?...`
生产由 Caddy TLS 反代到本进程(与 `game.xworld.ren` 部署方式一致)。
## 构建(Windows / VS2022)
```powershell
cd D:\UD\AI\AIGame\AIServer
cmake -S . -B build -G "Visual Studio 17 2022" -A x64
cmake --build build --config Release
```
产物:`build\Release\aiserver.exe`
## 运行
```powershell
cd D:\UD\AI\AIGame\AIServer\build\Release
.\aiserver.exe --host 0.0.0.0 --port 8080 --db ..\..\data\aiserver.db
```
## 客户端联调
Unity 菜单或 Boot 配置:
- HttpBase: `http://127.0.0.1:8080`
- WsUrlTemplate: `ws://127.0.0.1:8080/ws?pid={pid}&token={token}`
## 数据
SQLite 文件默认 `AIServer/data/aiserver.db`(用户表 + token 表)。
+98
View File
@@ -0,0 +1,98 @@
#include "auth.hpp"
#include "crypto.hpp"
#include "json.hpp"
#include <cctype>
#include <ctime>
namespace auth {
namespace {
using nlohmann::json;
bool valid_username(const std::string& u) {
if (u.size() < 2 || u.size() > 64) return false;
for (unsigned char c : u) {
if (!(std::isalnum(c) || c == '_' || c == '-' || c == '.')) return false;
}
return true;
}
bool valid_password(const std::string& p) {
return p.size() >= 3 && p.size() <= 128;
}
std::string make_token(int64_t pid) {
const auto ts = static_cast<int64_t>(std::time(nullptr));
// 兼容线上探测格式:v1.<pid>.<unix>.<random>
return "v1." + std::to_string(pid) + "." + std::to_string(ts) + "." + crypto::random_token_part(24);
}
Result ok_token(int64_t pid, const std::string& token) {
Result r;
r.ok = true;
r.http_status = 200;
r.body = json{{"token", token}, {"pid", pid}}.dump();
return r;
}
Result err(int status, const std::string& code) {
Result r;
r.ok = false;
r.http_status = status;
r.body = json{{"error", code}}.dump();
return r;
}
} // namespace
Result register_user(db::Database& database, const std::string& username, const std::string& password) {
if (!valid_username(username) || !valid_password(password)) return err(400, "invalid_input");
if (database.find_user_by_name(username)) return err(409, "user_exists");
const auto salt = crypto::random_salt_hex(16);
const auto hash = crypto::sha256_hex(salt, password);
if (hash.empty()) return err(500, "hash_failed");
auto pid = database.create_user(username, hash, salt);
if (!pid) {
// unique race
if (database.find_user_by_name(username)) return err(409, "user_exists");
return err(500, "db_error");
}
const auto token = make_token(*pid);
const auto now = static_cast<int64_t>(std::time(nullptr));
const auto exp = now + 86400 * 30; // 30 days
if (!database.store_token(token, *pid, now, exp)) return err(500, "token_store_failed");
return ok_token(*pid, token);
}
Result login_user(db::Database& database, const std::string& username, const std::string& password) {
if (!valid_username(username) || !valid_password(password)) return err(400, "invalid_input");
auto user = database.find_user_by_name(username);
if (!user) return err(401, "invalid_credentials");
const auto hash = crypto::sha256_hex(user->salt, password);
if (hash.empty() || hash != user->password_hash) return err(401, "invalid_credentials");
const auto token = make_token(user->pid);
const auto now = static_cast<int64_t>(std::time(nullptr));
const auto exp = now + 86400 * 30;
database.purge_expired_tokens(now);
if (!database.store_token(token, user->pid, now, exp)) return err(500, "token_store_failed");
return ok_token(user->pid, token);
}
bool validate_ws(db::Database& database, int64_t pid, const std::string& token) {
if (token.empty()) return false;
auto tok_pid = database.pid_for_token(token);
if (!tok_pid) return false;
if (pid > 0 && *tok_pid != pid) return false;
return true;
}
} // namespace auth
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include "db.hpp"
#include <string>
namespace auth {
struct Result {
bool ok = false;
int http_status = 500;
std::string body; // JSON
};
Result register_user(db::Database& database, const std::string& username, const std::string& password);
Result login_user(db::Database& database, const std::string& username, const std::string& password);
// Validate token matches pid (pid may be 0 to skip pid check).
bool validate_ws(db::Database& database, int64_t pid, const std::string& token);
} // namespace auth
+142
View File
@@ -0,0 +1,142 @@
#include "crypto.hpp"
#include <array>
#include <cstdio>
#include <random>
#include <sstream>
#include <iomanip>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#include <bcrypt.h>
#pragma comment(lib, "bcrypt.lib")
#else
#include <openssl/sha.h> // fallback not used on Windows path
#endif
namespace crypto {
namespace {
constexpr char kWsMagic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
std::string to_hex(const uint8_t* data, size_t n) {
std::ostringstream oss;
oss << std::hex << std::setfill('0');
for (size_t i = 0; i < n; ++i) oss << std::setw(2) << static_cast<int>(data[i]);
return oss.str();
}
std::string b64_encode(const uint8_t* data, size_t len) {
static const char* tbl =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
out.reserve(((len + 2) / 3) * 4);
size_t i = 0;
while (i + 2 < len) {
uint32_t n = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2];
out.push_back(tbl[(n >> 18) & 63]);
out.push_back(tbl[(n >> 12) & 63]);
out.push_back(tbl[(n >> 6) & 63]);
out.push_back(tbl[n & 63]);
i += 3;
}
if (i < len) {
uint32_t n = data[i] << 16;
out.push_back(tbl[(n >> 18) & 63]);
if (i + 1 < len) {
n |= data[i + 1] << 8;
out.push_back(tbl[(n >> 12) & 63]);
out.push_back(tbl[(n >> 6) & 63]);
out.push_back('=');
} else {
out.push_back(tbl[(n >> 12) & 63]);
out.push_back('=');
out.push_back('=');
}
}
return out;
}
#ifdef _WIN32
bool bcrypt_hash(const wchar_t* alg, const uint8_t* in, size_t in_len, std::vector<uint8_t>& out) {
BCRYPT_ALG_HANDLE hAlg = nullptr;
BCRYPT_HASH_HANDLE hHash = nullptr;
DWORD hashObjLen = 0, hashLen = 0, cb = 0;
if (BCryptOpenAlgorithmProvider(&hAlg, alg, nullptr, 0) != 0) return false;
BCryptGetProperty(hAlg, BCRYPT_OBJECT_LENGTH, reinterpret_cast<PUCHAR>(&hashObjLen), sizeof(DWORD), &cb, 0);
BCryptGetProperty(hAlg, BCRYPT_HASH_LENGTH, reinterpret_cast<PUCHAR>(&hashLen), sizeof(DWORD), &cb, 0);
std::vector<uint8_t> hashObj(hashObjLen);
out.assign(hashLen, 0);
bool ok = BCryptCreateHash(hAlg, &hHash, hashObj.data(), hashObjLen, nullptr, 0, 0) == 0 &&
BCryptHashData(hHash, reinterpret_cast<PUCHAR>(const_cast<uint8_t*>(in)), static_cast<ULONG>(in_len), 0) == 0 &&
BCryptFinishHash(hHash, out.data(), hashLen, 0) == 0;
if (hHash) BCryptDestroyHash(hHash);
if (hAlg) BCryptCloseAlgorithmProvider(hAlg, 0);
return ok;
}
#endif
} // namespace
std::string sha256_hex(const std::string& data) {
#ifdef _WIN32
std::vector<uint8_t> dig;
if (!bcrypt_hash(BCRYPT_SHA256_ALGORITHM, reinterpret_cast<const uint8_t*>(data.data()), data.size(), dig))
return {};
return to_hex(dig.data(), dig.size());
#else
unsigned char dig[SHA256_DIGEST_LENGTH];
SHA256(reinterpret_cast<const unsigned char*>(data.data()), data.size(), dig);
return to_hex(dig, SHA256_DIGEST_LENGTH);
#endif
}
std::string sha256_hex(const std::string& salt, const std::string& password) {
return sha256_hex(salt + ":" + password);
}
std::string websocket_accept_key(const std::string& client_key) {
std::string src = client_key + kWsMagic;
#ifdef _WIN32
std::vector<uint8_t> dig;
if (!bcrypt_hash(BCRYPT_SHA1_ALGORITHM, reinterpret_cast<const uint8_t*>(src.data()), src.size(), dig))
return {};
return b64_encode(dig.data(), dig.size());
#else
unsigned char dig[SHA_DIGEST_LENGTH];
SHA1(reinterpret_cast<const unsigned char*>(src.data()), src.size(), dig);
return b64_encode(dig, SHA_DIGEST_LENGTH);
#endif
}
std::string random_bytes_hex(size_t nbytes) {
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<int> dist(0, 255);
std::vector<uint8_t> buf(nbytes);
for (auto& b : buf) b = static_cast<uint8_t>(dist(gen));
// url-safe-ish base64 without padding for token part
auto s = b64_encode(buf.data(), buf.size());
for (char& c : s) {
if (c == '+') c = '-';
else if (c == '/') c = '_';
}
while (!s.empty() && s.back() == '=') s.pop_back();
return s;
}
std::string random_token_part(size_t nbytes) { return random_bytes_hex(nbytes); }
std::string random_salt_hex(size_t nbytes) {
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<int> dist(0, 255);
std::vector<uint8_t> buf(nbytes);
for (auto& b : buf) b = static_cast<uint8_t>(dist(gen));
return to_hex(buf.data(), buf.size());
}
} // namespace crypto
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace crypto {
std::string sha256_hex(const std::string& data);
std::string sha256_hex(const std::string& salt, const std::string& password);
// WebSocket accept: Base64(SHA1(key + magic))
std::string websocket_accept_key(const std::string& client_key);
std::string random_token_part(size_t nbytes = 24);
std::string random_salt_hex(size_t nbytes = 16);
} // namespace crypto
+169
View File
@@ -0,0 +1,169 @@
#include "db.hpp"
#include "sqlite3.h"
#include <ctime>
namespace db {
Database::Database(const std::string& path) {
if (sqlite3_open(path.c_str(), &db_) != SQLITE_OK) {
err_ = db_ ? sqlite3_errmsg(db_) : "sqlite3_open failed";
if (db_) {
sqlite3_close(db_);
db_ = nullptr;
}
return;
}
exec("PRAGMA journal_mode=WAL;");
exec("PRAGMA foreign_keys=ON;");
const char* schema = R"SQL(
CREATE TABLE IF NOT EXISTS users (
pid INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
password_hash TEXT NOT NULL,
salt TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS tokens (
token TEXT PRIMARY KEY,
pid INTEGER NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
FOREIGN KEY(pid) REFERENCES users(pid) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_tokens_pid ON tokens(pid);
)SQL";
if (!exec(schema)) {
sqlite3_close(db_);
db_ = nullptr;
}
}
Database::~Database() {
if (db_) sqlite3_close(db_);
}
bool Database::exec(const char* sql) {
char* errmsg = nullptr;
if (sqlite3_exec(db_, sql, nullptr, nullptr, &errmsg) != SQLITE_OK) {
err_ = errmsg ? errmsg : "exec failed";
if (errmsg) sqlite3_free(errmsg);
return false;
}
return true;
}
std::optional<int64_t> Database::create_user(const std::string& username, const std::string& password_hash,
const std::string& salt) {
const char* sql =
"INSERT INTO users(username, password_hash, salt, created_at) VALUES(?,?,?,?);";
sqlite3_stmt* st = nullptr;
if (sqlite3_prepare_v2(db_, sql, -1, &st, nullptr) != SQLITE_OK) {
err_ = sqlite3_errmsg(db_);
return std::nullopt;
}
const auto now = static_cast<int64_t>(std::time(nullptr));
sqlite3_bind_text(st, 1, username.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 2, password_hash.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 3, salt.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int64(st, 4, now);
const int rc = sqlite3_step(st);
sqlite3_finalize(st);
if (rc != SQLITE_DONE) {
err_ = sqlite3_errmsg(db_);
return std::nullopt;
}
return static_cast<int64_t>(sqlite3_last_insert_rowid(db_));
}
std::optional<User> Database::find_user_by_name(const std::string& username) {
const char* sql = "SELECT pid, username, password_hash, salt FROM users WHERE username=? COLLATE NOCASE LIMIT 1;";
sqlite3_stmt* st = nullptr;
if (sqlite3_prepare_v2(db_, sql, -1, &st, nullptr) != SQLITE_OK) {
err_ = sqlite3_errmsg(db_);
return std::nullopt;
}
sqlite3_bind_text(st, 1, username.c_str(), -1, SQLITE_TRANSIENT);
std::optional<User> u;
if (sqlite3_step(st) == SQLITE_ROW) {
User user;
user.pid = sqlite3_column_int64(st, 0);
user.username = reinterpret_cast<const char*>(sqlite3_column_text(st, 1));
user.password_hash = reinterpret_cast<const char*>(sqlite3_column_text(st, 2));
user.salt = reinterpret_cast<const char*>(sqlite3_column_text(st, 3));
u = std::move(user);
}
sqlite3_finalize(st);
return u;
}
std::optional<User> Database::find_user_by_pid(int64_t pid) {
const char* sql = "SELECT pid, username, password_hash, salt FROM users WHERE pid=? LIMIT 1;";
sqlite3_stmt* st = nullptr;
if (sqlite3_prepare_v2(db_, sql, -1, &st, nullptr) != SQLITE_OK) {
err_ = sqlite3_errmsg(db_);
return std::nullopt;
}
sqlite3_bind_int64(st, 1, pid);
std::optional<User> u;
if (sqlite3_step(st) == SQLITE_ROW) {
User user;
user.pid = sqlite3_column_int64(st, 0);
user.username = reinterpret_cast<const char*>(sqlite3_column_text(st, 1));
user.password_hash = reinterpret_cast<const char*>(sqlite3_column_text(st, 2));
user.salt = reinterpret_cast<const char*>(sqlite3_column_text(st, 3));
u = std::move(user);
}
sqlite3_finalize(st);
return u;
}
bool Database::store_token(const std::string& token, int64_t pid, int64_t created_at, int64_t expires_at) {
const char* sql = "INSERT OR REPLACE INTO tokens(token, pid, created_at, expires_at) VALUES(?,?,?,?);";
sqlite3_stmt* st = nullptr;
if (sqlite3_prepare_v2(db_, sql, -1, &st, nullptr) != SQLITE_OK) {
err_ = sqlite3_errmsg(db_);
return false;
}
sqlite3_bind_text(st, 1, token.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int64(st, 2, pid);
sqlite3_bind_int64(st, 3, created_at);
sqlite3_bind_int64(st, 4, expires_at);
const int rc = sqlite3_step(st);
sqlite3_finalize(st);
if (rc != SQLITE_DONE) {
err_ = sqlite3_errmsg(db_);
return false;
}
return true;
}
std::optional<int64_t> Database::pid_for_token(const std::string& token) {
const char* sql = "SELECT pid, expires_at FROM tokens WHERE token=? LIMIT 1;";
sqlite3_stmt* st = nullptr;
if (sqlite3_prepare_v2(db_, sql, -1, &st, nullptr) != SQLITE_OK) {
err_ = sqlite3_errmsg(db_);
return std::nullopt;
}
sqlite3_bind_text(st, 1, token.c_str(), -1, SQLITE_TRANSIENT);
std::optional<int64_t> pid;
if (sqlite3_step(st) == SQLITE_ROW) {
const auto expires = sqlite3_column_int64(st, 1);
const auto now = static_cast<int64_t>(std::time(nullptr));
if (expires >= now) pid = sqlite3_column_int64(st, 0);
}
sqlite3_finalize(st);
return pid;
}
void Database::purge_expired_tokens(int64_t now) {
sqlite3_stmt* st = nullptr;
if (sqlite3_prepare_v2(db_, "DELETE FROM tokens WHERE expires_at < ?;", -1, &st, nullptr) != SQLITE_OK)
return;
sqlite3_bind_int64(st, 1, now);
sqlite3_step(st);
sqlite3_finalize(st);
}
} // namespace db
+44
View File
@@ -0,0 +1,44 @@
#pragma once
#include <cstdint>
#include <optional>
#include <string>
struct sqlite3;
namespace db {
struct User {
int64_t pid = 0;
std::string username;
std::string password_hash;
std::string salt;
};
class Database {
public:
explicit Database(const std::string& path);
~Database();
Database(const Database&) = delete;
Database& operator=(const Database&) = delete;
bool open_ok() const { return db_ != nullptr; }
const std::string& last_error() const { return err_; }
// returns pid on success
std::optional<int64_t> create_user(const std::string& username, const std::string& password_hash,
const std::string& salt);
std::optional<User> find_user_by_name(const std::string& username);
std::optional<User> find_user_by_pid(int64_t pid);
bool store_token(const std::string& token, int64_t pid, int64_t created_at, int64_t expires_at);
std::optional<int64_t> pid_for_token(const std::string& token);
void purge_expired_tokens(int64_t now);
private:
bool exec(const char* sql);
sqlite3* db_ = nullptr;
std::string err_;
};
} // namespace db
+440
View File
@@ -0,0 +1,440 @@
#include "http_ws_server.hpp"
#include "auth.hpp"
#include "crypto.hpp"
#include "json.hpp"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using socket_t = SOCKET;
static constexpr socket_t kInvalid = INVALID_SOCKET;
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
using socket_t = int;
static constexpr socket_t kInvalid = -1;
#endif
namespace {
void closesock(socket_t s) {
#ifdef _WIN32
closesocket(s);
#else
close(s);
#endif
}
bool send_all(socket_t s, const char* data, size_t len) {
size_t sent = 0;
while (sent < len) {
#ifdef _WIN32
const int n = ::send(s, data + sent, static_cast<int>(len - sent), 0);
#else
const ssize_t n = ::send(s, data + sent, len - sent, 0);
#endif
if (n <= 0) return false;
sent += static_cast<size_t>(n);
}
return true;
}
bool recv_some(socket_t s, std::string& buf, size_t max_extra = 64 * 1024) {
char tmp[4096];
#ifdef _WIN32
const int n = ::recv(s, tmp, sizeof(tmp), 0);
#else
const ssize_t n = ::recv(s, tmp, sizeof(tmp), 0);
#endif
if (n <= 0) return false;
if (buf.size() + static_cast<size_t>(n) > max_extra) return false;
buf.append(tmp, static_cast<size_t>(n));
return true;
}
std::string to_lower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return s;
}
struct HttpRequest {
std::string method;
std::string path;
std::string query;
std::map<std::string, std::string> headers;
std::string body;
};
bool parse_request(const std::string& raw, HttpRequest& out) {
const auto pos = raw.find("\r\n\r\n");
if (pos == std::string::npos) return false;
const std::string head = raw.substr(0, pos);
out.body = raw.substr(pos + 4);
std::istringstream iss(head);
std::string line;
if (!std::getline(iss, line)) return false;
if (!line.empty() && line.back() == '\r') line.pop_back();
{
std::istringstream ls(line);
std::string url;
ls >> out.method >> url;
const auto q = url.find('?');
if (q == std::string::npos) {
out.path = url;
} else {
out.path = url.substr(0, q);
out.query = url.substr(q + 1);
}
}
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
const auto c = line.find(':');
if (c == std::string::npos) continue;
auto key = to_lower(line.substr(0, c));
auto val = line.substr(c + 1);
while (!val.empty() && (val.front() == ' ' || val.front() == '\t')) val.erase(val.begin());
out.headers[key] = val;
}
return true;
}
std::map<std::string, std::string> parse_query(const std::string& q) {
std::map<std::string, std::string> m;
size_t i = 0;
while (i < q.size()) {
size_t amp = q.find('&', i);
if (amp == std::string::npos) amp = q.size();
auto part = q.substr(i, amp - i);
const auto eq = part.find('=');
if (eq == std::string::npos) m[part] = "";
else m[part.substr(0, eq)] = part.substr(eq + 1);
i = amp + 1;
}
return m;
}
std::string url_decode(const std::string& s) {
std::string o;
o.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '%' && i + 2 < s.size()) {
const auto hex = s.substr(i + 1, 2);
char* end = nullptr;
const long v = std::strtol(hex.c_str(), &end, 16);
if (end && *end == 0) {
o.push_back(static_cast<char>(v));
i += 2;
continue;
}
} else if (s[i] == '+') {
o.push_back(' ');
continue;
}
o.push_back(s[i]);
}
return o;
}
std::string http_response(int status, const std::string& status_text, const std::string& body,
const std::string& content_type = "application/json; charset=utf-8") {
std::ostringstream oss;
oss << "HTTP/1.1 " << status << " " << status_text << "\r\n";
oss << "Content-Type: " << content_type << "\r\n";
oss << "Content-Length: " << body.size() << "\r\n";
oss << "Connection: close\r\n";
oss << "Access-Control-Allow-Origin: *\r\n";
oss << "\r\n";
oss << body;
return oss.str();
}
bool is_ws_upgrade(const HttpRequest& req) {
auto it = req.headers.find("upgrade");
if (it == req.headers.end()) return false;
return to_lower(it->second).find("websocket") != std::string::npos;
}
bool send_ws_text(socket_t s, const std::string& text) {
// server->client: unmasked
std::vector<uint8_t> frame;
frame.push_back(0x81); // FIN + text
const size_t n = text.size();
if (n < 126) {
frame.push_back(static_cast<uint8_t>(n));
} else if (n <= 0xFFFF) {
frame.push_back(126);
frame.push_back(static_cast<uint8_t>((n >> 8) & 0xFF));
frame.push_back(static_cast<uint8_t>(n & 0xFF));
} else {
frame.push_back(127);
for (int i = 7; i >= 0; --i) frame.push_back(static_cast<uint8_t>((n >> (8 * i)) & 0xFF));
}
frame.insert(frame.end(), text.begin(), text.end());
return send_all(s, reinterpret_cast<const char*>(frame.data()), frame.size());
}
void ws_loop(socket_t s) {
std::vector<uint8_t> buf;
buf.reserve(8192);
while (true) {
char tmp[4096];
#ifdef _WIN32
const int n = ::recv(s, tmp, sizeof(tmp), 0);
#else
const ssize_t n = ::recv(s, tmp, sizeof(tmp), 0);
#endif
if (n <= 0) break;
buf.insert(buf.end(), tmp, tmp + n);
while (buf.size() >= 2) {
const uint8_t b0 = buf[0];
const uint8_t b1 = buf[1];
const bool fin = (b0 & 0x80) != 0;
const uint8_t opcode = b0 & 0x0F;
const bool masked = (b1 & 0x80) != 0;
uint64_t payload_len = b1 & 0x7F;
size_t header = 2;
if (payload_len == 126) {
if (buf.size() < 4) break;
payload_len = (static_cast<uint64_t>(buf[2]) << 8) | buf[3];
header = 4;
} else if (payload_len == 127) {
if (buf.size() < 10) break;
payload_len = 0;
for (int i = 0; i < 8; ++i) payload_len = (payload_len << 8) | buf[2 + i];
header = 10;
}
const size_t mask_len = masked ? 4 : 0;
if (buf.size() < header + mask_len + payload_len) break;
std::string payload;
payload.resize(static_cast<size_t>(payload_len));
const size_t data_off = header + mask_len;
if (masked) {
const uint8_t* mask = buf.data() + header;
for (uint64_t i = 0; i < payload_len; ++i)
payload[static_cast<size_t>(i)] = static_cast<char>(buf[data_off + static_cast<size_t>(i)] ^ mask[i % 4]);
} else {
std::memcpy(payload.data(), buf.data() + data_off, static_cast<size_t>(payload_len));
}
buf.erase(buf.begin(), buf.begin() + static_cast<std::ptrdiff_t>(header + mask_len + payload_len));
if (opcode == 0x8) { // close
return;
}
if (opcode == 0x9) { // ping -> pong
std::vector<uint8_t> pong;
pong.push_back(0x8A);
pong.push_back(static_cast<uint8_t>(payload.size()));
pong.insert(pong.end(), payload.begin(), payload.end());
send_all(s, reinterpret_cast<const char*>(pong.data()), pong.size());
continue;
}
if (opcode == 0x1 && fin) {
// echo hello ack for app-level handshake
try {
auto j = nlohmann::json::parse(payload);
if (j.contains("op") && j["op"] == "hello") {
nlohmann::json ack{{"op", "hello_ack"}, {"ok", true}};
send_ws_text(s, ack.dump());
} else if (j.contains("op") && j["op"] == "ping") {
send_ws_text(s, nlohmann::json{{"op", "pong"}}.dump());
}
} catch (...) {
// ignore non-json
}
}
}
}
}
} // namespace
HttpWsServer::HttpWsServer(db::Database& db, std::string host, uint16_t port)
: db_(db), host_(std::move(host)), port_(port) {}
HttpWsServer::~HttpWsServer() { stop(); }
bool HttpWsServer::start() {
#ifdef _WIN32
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return false;
#endif
listen_sock_ = static_cast<uintptr_t>(::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
auto s = static_cast<socket_t>(listen_sock_);
if (s == kInvalid) return false;
int yes = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&yes), sizeof(yes));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port_);
if (host_ == "0.0.0.0" || host_.empty()) {
addr.sin_addr.s_addr = htonl(INADDR_ANY);
} else {
inet_pton(AF_INET, host_.c_str(), &addr.sin_addr);
}
if (bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
closesock(s);
listen_sock_ = static_cast<uintptr_t>(-1);
return false;
}
if (listen(s, 128) != 0) {
closesock(s);
listen_sock_ = static_cast<uintptr_t>(-1);
return false;
}
running_ = true;
accept_thread_ = std::thread([this] { accept_loop(); });
return true;
}
void HttpWsServer::stop() {
running_ = false;
if (listen_sock_ != static_cast<uintptr_t>(-1)) {
closesock(static_cast<socket_t>(listen_sock_));
listen_sock_ = static_cast<uintptr_t>(-1);
}
if (accept_thread_.joinable()) accept_thread_.join();
#ifdef _WIN32
// WSACleanup 可能被多次调用;此处简单处理
#endif
}
void HttpWsServer::accept_loop() {
auto ls = static_cast<socket_t>(listen_sock_);
while (running_) {
sockaddr_in cli{};
#ifdef _WIN32
int len = sizeof(cli);
#else
socklen_t len = sizeof(cli);
#endif
socket_t cs = ::accept(ls, reinterpret_cast<sockaddr*>(&cli), &len);
if (cs == kInvalid) {
if (!running_) break;
continue;
}
std::thread([this, cs] {
handle_client(static_cast<uintptr_t>(cs));
closesock(cs);
}).detach();
}
}
void HttpWsServer::handle_client(uintptr_t client_sock) {
auto s = static_cast<socket_t>(client_sock);
std::string raw;
// read headers
while (raw.find("\r\n\r\n") == std::string::npos) {
if (!recv_some(s, raw, 256 * 1024)) return;
}
HttpRequest req;
if (!parse_request(raw, req)) {
auto resp = http_response(400, "Bad Request", "{\"error\":\"bad_request\"}");
send_all(s, resp.data(), resp.size());
return;
}
// read remaining body by Content-Length
auto cl_it = req.headers.find("content-length");
size_t content_length = 0;
if (cl_it != req.headers.end()) content_length = static_cast<size_t>(std::strtoull(cl_it->second.c_str(), nullptr, 10));
while (req.body.size() < content_length) {
if (!recv_some(s, raw, 1024 * 1024)) return;
const auto pos = raw.find("\r\n\r\n");
req.body = raw.substr(pos + 4);
}
if (content_length > 0 && req.body.size() > content_length) req.body.resize(content_length);
// WebSocket upgrade
if (req.path == "/ws" && is_ws_upgrade(req)) {
auto q = parse_query(req.query);
const std::string token = url_decode(q.count("token") ? q["token"] : "");
int64_t pid = 0;
if (q.count("pid") && !q["pid"].empty()) pid = std::strtoll(q["pid"].c_str(), nullptr, 10);
if (!auth::validate_ws(db_, pid, token)) {
auto resp = http_response(401, "Unauthorized", "{\"error\":\"unauthorized\"}");
send_all(s, resp.data(), resp.size());
return;
}
auto key_it = req.headers.find("sec-websocket-key");
if (key_it == req.headers.end()) {
auto resp = http_response(400, "Bad Request", "{\"error\":\"missing_ws_key\"}");
send_all(s, resp.data(), resp.size());
return;
}
const auto accept = crypto::websocket_accept_key(key_it->second);
std::ostringstream oss;
oss << "HTTP/1.1 101 Switching Protocols\r\n"
<< "Upgrade: websocket\r\n"
<< "Connection: Upgrade\r\n"
<< "Sec-WebSocket-Accept: " << accept << "\r\n"
<< "\r\n";
const auto resp = oss.str();
if (!send_all(s, resp.data(), resp.size())) return;
std::printf("[ws] open pid=%lld\n", static_cast<long long>(pid));
ws_loop(s);
std::printf("[ws] close pid=%lld\n", static_cast<long long>(pid));
return;
}
// HTTP API
if (req.method == "POST" && (req.path == "/register" || req.path == "/login")) {
std::string username, password;
try {
auto j = nlohmann::json::parse(req.body.empty() ? "{}" : req.body);
username = j.value("username", "");
password = j.value("password", "");
} catch (...) {
auto resp = http_response(400, "Bad Request", "{\"error\":\"invalid_input\"}");
send_all(s, resp.data(), resp.size());
return;
}
auth::Result r =
(req.path == "/register") ? auth::register_user(db_, username, password) : auth::login_user(db_, username, password);
const char* st = r.http_status == 200 ? "OK"
: r.http_status == 400 ? "Bad Request"
: r.http_status == 401 ? "Unauthorized"
: r.http_status == 409 ? "Conflict"
: "Error";
auto resp = http_response(r.http_status, st, r.body);
send_all(s, resp.data(), resp.size());
return;
}
if (req.method == "GET" && req.path == "/health") {
auto resp = http_response(200, "OK", "{\"ok\":true,\"service\":\"aiserver\"}");
send_all(s, resp.data(), resp.size());
return;
}
auto resp = http_response(404, "Not Found", "{\"error\":\"not_found\"}");
send_all(s, resp.data(), resp.size());
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include "db.hpp"
#include <atomic>
#include <cstdint>
#include <string>
#include <thread>
class HttpWsServer {
public:
HttpWsServer(db::Database& db, std::string host, uint16_t port);
~HttpWsServer();
bool start();
void stop();
bool running() const { return running_; }
private:
void accept_loop();
void handle_client(uintptr_t client_sock);
db::Database& db_;
std::string host_;
uint16_t port_;
std::atomic<bool> running_{false};
uintptr_t listen_sock_ = static_cast<uintptr_t>(-1);
std::thread accept_thread_;
};
+70
View File
@@ -0,0 +1,70 @@
#include "db.hpp"
#include "http_ws_server.hpp"
#include <chrono>
#include <cstdio>
#include <filesystem>
#include <string>
#include <thread>
namespace fs = std::filesystem;
static void usage(const char* argv0) {
std::printf("Usage: %s [--host 0.0.0.0] [--port 8080] [--db data/aiserver.db] [--daemon]\n", argv0);
}
int main(int argc, char** argv) {
std::string host = "0.0.0.0";
uint16_t port = 8080;
std::string db_path = "data/aiserver.db";
bool daemon = false;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
if (a == "--host" && i + 1 < argc) host = argv[++i];
else if (a == "--port" && i + 1 < argc) port = static_cast<uint16_t>(std::stoi(argv[++i]));
else if (a == "--db" && i + 1 < argc) db_path = argv[++i];
else if (a == "--daemon") daemon = true;
else if (a == "-h" || a == "--help") {
usage(argv[0]);
return 0;
} else {
std::printf("Unknown arg: %s\n", a.c_str());
usage(argv[0]);
return 1;
}
}
try {
fs::create_directories(fs::path(db_path).parent_path());
} catch (...) {
}
db::Database database(db_path);
if (!database.open_ok()) {
std::printf("DB open failed: %s path=%s\n", database.last_error().c_str(), db_path.c_str());
return 1;
}
HttpWsServer server(database, host, port);
if (!server.start()) {
std::printf("Listen failed on %s:%u\n", host.c_str(), static_cast<unsigned>(port));
return 1;
}
std::printf("AIServer listening http://%s:%u (POST /register /login, WS /ws?pid=&token=)\n",
host.c_str(), static_cast<unsigned>(port));
std::printf("DB=%s\n", db_path.c_str());
if (daemon) {
std::printf("daemon mode: running until process killed\n");
while (server.running()) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
} else {
std::printf("Press Enter to stop...\n");
std::getchar();
server.stop();
}
return 0;
}
+10255
View File
File diff suppressed because it is too large Load Diff
+24765
View File
File diff suppressed because it is too large Load Diff
+257679
View File
File diff suppressed because it is too large Load Diff
+13425
View File
File diff suppressed because it is too large Load Diff
+22 -8
View File
@@ -1,25 +1,39 @@
# 游戏服协议(M2 探测结论)
# 游戏服协议
Base: `https://game.xworld.ren`(Caddy → Kestrel)
## 生产
Base: `https://game.xworld.ren`(Caddy → 后端)
## 本地 AIServer(推荐开发)
路径:`AIServer/`(C++ + SQLite)
| Base | `http://127.0.0.1:8080` |
| WS | `ws://127.0.0.1:8080/ws?pid={pid}&token={token}` |
构建与运行见 [`AIServer/README.md`](../AIServer/README.md)。
## HTTP
| 方法 | 路径 | Body | 成功 | 失败 |
| --- | --- | --- | --- | --- |
| POST | `/register` | `{"username","password"}` | `{token,pid}` | `invalid_input` 等 |
| POST | `/register` | `{"username","password"}` | `{token,pid}` | `invalid_input` / `user_exists` |
| POST | `/login` | `{"username","password"}` | `{token,pid}` | `invalid_credentials` |
| GET | `/health` | — | `{ok,service}` | — |
## WebSocket
```
wss://game.xworld.ren/ws?pid={pid}&token={token}
/ws?pid={pid}&token={token}
```
- 无 token → HTTP 401(握手阶段拒绝)
- 连通后服务端可不主动推消息;客户端可用 WebSocket 协议层 KeepAlive
- 应用层可发 `{"op":"hello",...}`(当前服可无应答)
- 无 token / token 无效 → HTTP 401
- 应用层:`{"op":"hello"}` → `{"op":"hello_ack","ok":true}`;`{"op":"ping"}` → `{"op":"pong"}`
- 协议层 Ping/Pong 由服务端应答
## 客户端
- `HotUpdate.Net.AuthApi` / `GameNet` / `WsClient`
- 编辑器自动 `guest_{deviceId}` 账号(PlayerPrefs 持久化 deviceId)
- Boot:`HttpBase` + `WsUrlTemplate`
- 菜单:**AIGame/Boot/Server/Local AIServer :8080** 或 Production
- 编辑器自动 `guest_{deviceId}` 账号
+9
View File
@@ -2,5 +2,14 @@
3D 模型及相关烘焙贴图。每条包含:路径、简要说明。
约定:游戏用角色放在 `AIClient/Assets/Bundles/Characters/{ActorName}/`(YooAsset Art / `PackDirectory`)。
| 资源路径 | 简要说明 |
| --- | --- |
| `AIClient/Assets/Bundles/Characters/MaleExplorer/` | 角色 MaleExplorer 目录(寻址 Prefab=`MaleExplorer`) |
| `…/MaleExplorer.fbx` | 混元高模减面低模(约 5k tris) |
| `…/MaleExplorer_*.png` | color / normal / ao / metallic / roughness 烘焙贴图 |
| `…/concept.png` | 图生3D 概念参考图 |
| `…/MaleExplorer.prefab` | 运行时加载 Prefab(菜单 `AIGame/M3/Setup Character…` 生成) |
| `Tools/output/male_explorer_3d/male_explorer.glb` | 混元高模中间件(不进 Bundle) |
| `Tools/output/male_explorer_game/` | 减面/烘焙中间输出(不进 Bundle) |
+2
View File
@@ -11,6 +11,8 @@
| `AIClient/Assets/Bundles/UI/Font/siyuan_CN_Bold SDF.asset` | TMP 动态 SDF 字体资源;JSON→Prefab 默认使用;菜单 `Tools/UI/Ensure SiYuan TMP Font Asset` |
| `Tools/output/male_explorer_test.png` | 男性探险者角色试做;项目文生图脚本 |
| `Tools/output/male_explorer_cursor.png` | 男性探险者对照;Cursor GenerateImage |
| `AIClient/Assets/Bundles/Characters/MaleExplorer/concept.png` | MaleExplorer 概念图(进角色目录) |
| `AIClient/Assets/Bundles/Characters/MaleExplorer/MaleExplorer_*.png` | 低模烘焙贴图(color/normal/ao/metallic/roughness) |
| `Doc/ui_design.jpg` | UI 视觉基准图;糖果休闲风控件参考(`Doc/Design/ui_design.jpg` 为同内容副本) |
| `Doc/UI_AutoGen_Overview.md` | UI 自动生成方案总览(JSON→Prefab + 图集) |
| `Doc/UIPrefabCreater/UI_ConfirmDialog.json` | 竖屏确认弹窗样例 JSON;对应 Prefab 路径 `Assets/Bundles/UI/Prefab/UI_ConfirmDialog.prefab` |
+30 -10
View File
@@ -51,7 +51,7 @@ python Tools/gpt_image_generate.py --json "{\"prompt\":\"UI图集\",\"output\":\
### 能力说明
1. 首期仅 **图生3D → GLB**。文生请先用上文「文/图生图」出图,再交给本脚本。
2. 未登录或凭证失效时,会 **弹出 Edge 微信扫码**(同步阻塞,最长 `--login-timeout` 秒),成功后自动续跑。
2. 未登录、凭证失效或**当前账号额度/次数用尽**时,会 **弹出 Edge 微信扫码页**(同步阻塞,最长 `--login-timeout` 秒);额度满时提示换号登录,成功后自动续跑。
3. 面数:`--faces 50k|500k|1m`(默认 `50k`)。
4. 任务中间文件在 `Tools/data/hunyuan/jobs/<job_id>/`;最终 GLB 写到 `-o`。
5. 生成完成后须在 `Doc/ResDesc_Model.md` 登记资源(索引见 `Doc/ResDesc.md`)。
@@ -64,7 +64,10 @@ python Tools/hunyuan_3d_generate.py --status
# 预登录(弹出微信扫码)
python Tools/hunyuan_3d_generate.py --login
# 图生3D(未登录则中途自动弹微信)
# 强制换号登录(忽略本地凭证 / 额度满换号)
python Tools/hunyuan_3d_generate.py --login --force-login
# 图生3D(未登录或额度满则中途自动弹登录页)
python Tools/hunyuan_3d_generate.py -i ref.png -o Tools/output/prop.glb --faces 50k
# JSON / Agent
@@ -77,6 +80,7 @@ python Tools/hunyuan_3d_generate.py -i ref.png -o out.glb --no-interactive-login
### 流程回调 / 事件
- `--callback-url` / `--callback-file` / NDJSON 与文生图脚本同模式
- 典型事件:`login_required` → `login_waiting` → `login_ok` → `stage` → `succeeded` / `failed`
- `login_required.reason`:`auth`(未登录/失效)或 `quota`(额度满需换号)
## 高模减面与贴图烘焙
- 来源:复刻 `ClientTrunk/Tools/ModelTools`(`model_decimate` + `model_bake`)
@@ -89,23 +93,39 @@ python Tools/hunyuan_3d_generate.py -i ref.png -o out.glb --no-interactive-login
高模(FBX / GLB / glTF)
-> 减面 + 重展 UV -> <名>_low.fbx
-> Cycles selected-to-active 烘焙
-> 低模 FBX + color / normal / ao / metallic / roughness PNG
-> 五通道 PNG + 低模 FBX
-> model_translator(默认)-> XPbr 两张图 + .mat/.meta
<名>_base.png RGB=Albedo A=AO/透明
<名>_mix.png RG=球面法线 B=Metallic A=Roughness
```
### AI / 命令行调用
```bash
# 一键(推荐):减面 + 烘焙
# 一键:减面 + 烘焙 + XPbr 打包(默认)
python Tools/model_tools/model_lowpoly_bake.py Tools/output/prop.glb -o Tools/output/prop_game --tris 5000 --size 2048
# 分步
python Tools/model_tools/model_decimate.py prop.glb --tris 5000 -o Tools/output/prop_low
python Tools/model_tools/model_bake.py prop.glb Tools/output/prop_low/prop_low.fbx -o Tools/output/prop_bake --size 2048
# 仅五通道、跳过 XPbr
python Tools/model_tools/model_lowpoly_bake.py prop.glb -o Tools/output/prop_game --no-xpbr
# JSON / Agent
python Tools/model_tools/model_lowpoly_bake.py --json "{\"high\":\"prop.glb\",\"out\":\"Tools/output/prop_game\",\"tris\":5000,\"size\":2048}" --result-only
# 单独 XPbr 转换(输入为烘焙后的 FBX 目录旁贴图)
python Tools/model_tools/model_translator.py Tools/output/prop_game/prop/prop.fbx -o Tools/output/prop_xpbr
```
与混元衔接:先 `hunyuan_3d_generate.py` 出高模 GLB,再对本脚本做低模烘焙;完成后登记 `Doc/ResDesc_Model.md`。
与混元衔接:
```bash
python Tools/hunyuan_3d_generate.py -i ref.png -o Tools/output/{actor}_3d/{actor}.glb --faces 50k
python Tools/model_tools/model_lowpoly_bake.py Tools/output/{actor}_3d/{actor}.glb -o Tools/output/{actor}_game --tris 5000 --size 2048
python Tools/install_character_bundles.py -a {ActorName} -b Tools/output/{actor}_game/{actor}_xpbr -c ref.png
# Unity: AIGame/M3/Setup Character Prefab + Art Collector(挂 Test/XPbr 生成预设)
```
### 与 AIC#Project ModelTranslator 对比(减面/烘焙)
- **更优(AIC#)**:默认 Quad Remesher 四边拓扑、更深 seam 扫描;本仓库未捆绑 QR 引擎。
- **已对齐**:自适应烘焙射线、UV 最大单岛门限、XPbr base/mix 打包与 `Test/XPbr` 材质。
- **本仓库优势**:高模直接吃 GLB/glTF(混元产物),一键流水线含 XPbr。
游戏目录:`AIClient/Assets/Bundles/Characters/{ActorName}/`;高模中间件留在 `Tools/output/`。完成后登记 `Doc/ResDesc_Model.md`。
## UI 自动生成(JSON → Prefab)
+3
View File
@@ -2,6 +2,7 @@
from .auth import ensure_login, is_logged_in, logout, start_wechat_login_blocking, status
from .client import FACE_LABELS, generate_from_image
from .errors import HunyuanQuotaExceeded, HunyuanReloginNeeded
__all__ = [
"ensure_login",
@@ -11,4 +12,6 @@ __all__ = [
"status",
"FACE_LABELS",
"generate_from_image",
"HunyuanQuotaExceeded",
"HunyuanReloginNeeded",
]
+98 -13
View File
@@ -1,6 +1,7 @@
"""WeChat login session for https://3d.hunyuan.tencent.com via Playwright.
CLI 友好:同步阻塞扫码登录(非后台线程)。
未登录 / 凭证失效 / 额度满换号 时弹出有头 Edge 供用户扫码。
"""
from __future__ import annotations
@@ -11,7 +12,7 @@ from pathlib import Path
from typing import Any, Callable, Optional
HUNYUAN_URL = "https://3d.hunyuan.tencent.com/"
LOGIN_TIMEOUT_SEC = 180
LOGIN_TIMEOUT_SEC = 300
UpdateFn = Callable[..., None]
@@ -140,32 +141,87 @@ def _looks_logged_in(page) -> bool:
has_generate = bool(page.get_by_text("立即生成").count())
except Exception:
pass
return bool((interesting or storage_hit) and has_generate)
# 有生成入口,且 cookie/storage 任一命中,或页面上已无「登录」
if has_generate and (interesting or storage_hit):
return True
if has_generate and not _page_shows_login_cta(page):
return True
return bool(interesting and storage_hit)
def _page_shows_login_cta(page) -> bool:
try:
if page.get_by_text("登录", exact=True).count():
return page.get_by_text("登录", exact=True).first.is_visible(timeout=300)
except Exception:
pass
return False
def _try_site_logout(page) -> None:
"""尽量在官网侧退出,方便额度满后换号扫码。"""
for label in ("退出登录", "退出", "登出", "注销"):
if _click_first(page, (label,), exact=False):
page.wait_for_timeout(800)
break
# 常见头像/用户菜单再点一次退出
try:
avatar = page.locator(
'[class*="avatar"], [class*="user-info"], [class*="UserInfo"]'
).first
if avatar.count() and avatar.is_visible(timeout=500):
avatar.click(timeout=2000)
page.wait_for_timeout(400)
_click_first(page, ("退出登录", "退出", "登出"), exact=False)
except Exception:
pass
def start_wechat_login_blocking(
timeout_sec: int = LOGIN_TIMEOUT_SEC,
*,
update: Optional[UpdateFn] = None,
reason: str = "auth",
clear_existing: bool = False,
) -> dict:
"""打开有头浏览器供微信扫码,阻塞直到成功 / 超时 / 失败。"""
"""打开有头浏览器供微信扫码,阻塞直到成功 / 超时 / 失败。
reason:
- auth: 未登录或凭证失效
- quota: 当前账号额度满,需换号
clear_existing: 先清本地会话;quota 场景会再尝试官网退出。
"""
from playwright.sync_api import sync_playwright
def _emit(event: str, **payload: Any) -> None:
if update:
update(event=event, **payload)
if clear_existing or reason == "quota":
logout()
if reason == "quota":
message = (
"当前混元账号额度/次数已满,请在弹出的浏览器中退出旧号并用微信扫码登录其他账号"
)
else:
message = "请在弹出的浏览器窗口中用微信扫码登录混元3D"
_write_status(
logged_in=False,
state="waiting_scan",
message="请在弹出的浏览器窗口中用微信扫码登录",
message=message,
reason=reason,
)
_emit(
"login_waiting",
stage="请在弹出的浏览器窗口中用微信扫码登录",
stage=message,
progress=5,
timeout_sec=timeout_sec,
reason=reason,
)
# 同步打到 stderr,方便 Agent/终端注意弹窗
print(f"[hunyuan] {message}(最长等待 {timeout_sec}s)", flush=True)
try:
with sync_playwright() as playwright:
@@ -177,8 +233,15 @@ def start_wechat_login_blocking(
)
page = context.new_page()
page.goto(HUNYUAN_URL, wait_until="domcontentloaded", timeout=60000)
page.wait_for_timeout(2500)
page.wait_for_timeout(2000)
if reason == "quota":
_try_site_logout(page)
page.goto(HUNYUAN_URL, wait_until="domcontentloaded", timeout=60000)
page.wait_for_timeout(1500)
_click_first(page, ("登录", "立即登录"), exact=True)
page.wait_for_timeout(800)
_click_first(page, ("微信", "微信登录", "微信扫码"), exact=False)
deadline = time.monotonic() + timeout_sec
@@ -187,15 +250,22 @@ def start_wechat_login_blocking(
session_dir().mkdir(parents=True, exist_ok=True)
context.storage_state(path=str(storage_state_path()))
result = _write_status(
logged_in=True, state="ready", message="微信登录成功"
logged_in=True,
state="ready",
message="微信登录成功",
reason=reason,
)
browser.close()
_emit("login_ok", stage="微信登录成功", progress=15, **result)
print("[hunyuan] 微信登录成功,会话已保存", flush=True)
return result
page.wait_for_timeout(1500)
result = _write_status(
logged_in=False, state="timeout", message="微信登录超时,请重试"
logged_in=False,
state="timeout",
message="微信登录超时,请重试",
reason=reason,
)
browser.close()
_emit("login_failed", stage="微信登录超时", progress=0, **result)
@@ -204,7 +274,7 @@ def start_wechat_login_blocking(
raise
except Exception as exc:
result = _write_status(
logged_in=False, state="error", message=f"登录失败:{exc}"
logged_in=False, state="error", message=f"登录失败:{exc}", reason=reason
)
_emit("login_failed", stage=str(exc), progress=0, **result)
raise RuntimeError(f"登录失败:{exc}") from exc
@@ -215,9 +285,14 @@ def ensure_login(
interactive: bool = True,
timeout_sec: int = LOGIN_TIMEOUT_SEC,
update: Optional[UpdateFn] = None,
force: bool = False,
reason: str = "auth",
) -> dict:
"""若无会话则弹微信登录;interactive=False 且未登录则抛错。"""
if is_logged_in():
"""若无会话则弹微信登录;interactive=False 且未登录则抛错。
force=True 时忽略本地凭证,强制打开登录页(换号 / 重登)。
"""
if is_logged_in() and not force:
current = status()
if update:
update(
@@ -234,7 +309,17 @@ def ensure_login(
if update:
update(
event="login_required",
stage="需要微信登录混元3D",
stage=(
"当前账号额度已满,需要换号登录"
if reason == "quota"
else "需要微信登录混元3D"
),
progress=2,
reason=reason,
)
return start_wechat_login_blocking(timeout_sec=timeout_sec, update=update)
return start_wechat_login_blocking(
timeout_sec=timeout_sec,
update=update,
reason=reason,
clear_existing=force or reason == "quota",
)
+201 -7
View File
@@ -9,6 +9,7 @@ from pathlib import Path
from typing import Callable, Optional
from .auth import HUNYUAN_URL, is_logged_in, storage_state_path
from .errors import HunyuanQuotaExceeded, HunyuanReloginNeeded
FACE_LABEL = "50k"
FACE_LABELS = ("50k", "500k", "1m")
@@ -17,6 +18,28 @@ POLL_INTERVAL_SEC = 5
API_LIST = "https://3d.hunyuan.tencent.com/api/3d/creations/list"
API_DETAIL = "https://3d.hunyuan.tencent.com/api/3d/creations/detail"
# 额度/次数用尽常见文案(页面 toast / 弹窗 / API message)
_QUOTA_PATTERNS = (
r"额度不足",
r"额度已用完",
r"额度已满",
r"额度已经用完",
r"次数不足",
r"次数已用完",
r"次数已达上限",
r"今日生成次数",
r"今日次数已用完",
r"已达上限",
r"积分不足",
r"免费次数.*?用完",
r"体验次数.*?用完",
r"生成次数不足",
r"没有剩余.*?次数",
r"剩余次数\s*[::]?\s*0",
r"insufficient\s*(quota|credit|balance)",
)
_QUOTA_RE = re.compile("|".join(_QUOTA_PATTERNS), re.I)
UpdateFn = Callable[..., None]
@@ -47,6 +70,123 @@ def _click_visible_text(page, labels, exact=False, timeout=5000):
return False
def _text_indicates_quota(text: str) -> bool:
if not text:
return False
return bool(_QUOTA_RE.search(text))
def _payload_indicates_quota(payload) -> Optional[str]:
"""从 generations / 其它 API JSON 中提取额度相关错误文案。"""
if payload is None:
return None
if isinstance(payload, str):
return payload if _text_indicates_quota(payload) else None
if isinstance(payload, dict):
for key in (
"message",
"msg",
"error",
"errorMsg",
"errorMessage",
"errMsg",
"reason",
"detail",
"tips",
"tip",
):
value = payload.get(key)
if isinstance(value, str) and _text_indicates_quota(value):
return value
if isinstance(value, (dict, list)):
found = _payload_indicates_quota(value)
if found:
return found
# code 类字段旁带 message
code = payload.get("code") or payload.get("ret") or payload.get("errorCode")
msg = payload.get("message") or payload.get("msg") or ""
if code not in (None, 0, "0", 200, "200", "Success", "success") and _text_indicates_quota(
str(msg)
):
return str(msg)
for key in ("data", "result", "error", "errors"):
found = _payload_indicates_quota(payload.get(key))
if found:
return found
if isinstance(payload, list):
for item in payload:
found = _payload_indicates_quota(item)
if found:
return found
return None
def _page_quota_message(page) -> Optional[str]:
"""优先从弹窗/toast 取额度提示,避免整页营销文案误判。"""
selectors = (
".t-dialog",
".t-message",
".t-notification",
"[class*='dialog']",
"[class*='toast']",
"[class*='message']",
"[role='dialog']",
"[role='alert']",
)
chunks: list[str] = []
for sel in selectors:
try:
locator = page.locator(sel)
total = min(locator.count(), 8)
except Exception:
continue
for index in range(total):
try:
node = locator.nth(index)
if not node.is_visible(timeout=200):
continue
text = (node.inner_text(timeout=500) or "").strip()
if text:
chunks.append(text)
except Exception:
continue
for text in chunks:
if _text_indicates_quota(text):
for line in text.splitlines():
line = line.strip()
if line and _text_indicates_quota(line):
return line[:200]
return text[:200]
try:
body = page.inner_text("body")
except Exception:
return None
# 整页仅在出现非常明确的「用完/不足」短句时判定
for line in body.splitlines():
line = line.strip()
if 4 <= len(line) <= 40 and _text_indicates_quota(line):
return line[:200]
return None
def _raise_if_quota(page=None, payloads=None, fallback: Optional[str] = None):
if payloads:
for payload in payloads:
found = _payload_indicates_quota(payload)
if found:
raise HunyuanQuotaExceeded(
f"混元账号额度不足:{found}。请换号登录后重试。"
)
if page is not None:
found = _page_quota_message(page)
if found:
raise HunyuanQuotaExceeded(
f"混元账号额度不足:{found}。请换号登录后重试。"
)
if fallback and _text_indicates_quota(fallback):
raise HunyuanQuotaExceeded(fallback)
def _dismiss_popups(page, log=None):
"""Close common confirm/agreement toasts that block generate submit."""
for label in ("我知道了", "知道了", "同意并继续", "同意", "确认", "继续", "关闭"):
@@ -54,6 +194,12 @@ def _dismiss_popups(page, log=None):
if log:
log.write(f"dismissed popup via 「{label}」\n")
page.wait_for_timeout(400)
# 协议点完后若仍是额度弹窗,再抛换号
quota_msg = _page_quota_message(page)
if quota_msg:
raise HunyuanQuotaExceeded(
f"混元账号额度不足:{quota_msg}。请换号登录后重试。"
)
def _click_generate(page, log=None):
@@ -202,8 +348,17 @@ def _dump_debug(page, directory: Path, log, network_hits):
def _api_json(request_context, method, url, **kwargs):
response = getattr(request_context, method)(url, **kwargs)
if response.status >= 400:
body_text = ""
try:
body_text = response.text()
except Exception:
pass
if response.status in (401, 403):
raise PermissionError(f"混元接口鉴权失败 {response.status}: {url}")
raise HunyuanReloginNeeded(f"混元接口鉴权失败 {response.status}: {url}")
if _text_indicates_quota(body_text):
raise HunyuanQuotaExceeded(
f"混元账号额度不足(HTTP {response.status}):{body_text[:200]}"
)
raise RuntimeError(f"混元接口失败 {response.status}: {url}")
try:
return response.json()
@@ -379,7 +534,7 @@ def _poll_until_ready(
waited = int(GENERATION_TIMEOUT_SEC - (deadline - time.monotonic()))
try:
detail = _detail_creation(request_context, creations_id)
except PermissionError:
except HunyuanReloginNeeded:
raise
except Exception:
listing = _list_creations(request_context)
@@ -432,10 +587,15 @@ def generate_from_image(
directory: Path,
update: UpdateFn,
face_label: str = FACE_LABEL,
*,
headed: bool = False,
) -> Path:
"""图生3D,返回 directory/generated.glb。鉴权失败抛 PermissionError。"""
"""图生3D,返回 directory/generated.glb。
鉴权失败抛 HunyuanReloginNeeded;额度满抛 HunyuanQuotaExceeded。
"""
if not is_logged_in():
raise PermissionError("尚未微信登录混元3D,请先登录。")
raise HunyuanReloginNeeded("尚未微信登录混元3D,请先登录。")
if face_label not in FACE_LABELS:
raise ValueError(f"面数须为 {FACE_LABELS} 之一,收到: {face_label}")
@@ -483,13 +643,16 @@ def generate_from_image(
if found:
creations_id = found
entry["creationsId"] = found
quota = _payload_indicates_quota(body)
if quota:
entry["quota"] = quota
except Exception:
pass
update(event="stage", stage="打开混元3D 网页", progress=20)
with log_path.open("w", encoding="utf-8") as log, sync_playwright() as playwright:
browser = playwright.chromium.launch(
channel=_browser_channel(), headless=True
channel=_browser_channel(), headless=not headed
)
context = browser.new_context(
storage_state=str(state_path),
@@ -505,7 +668,7 @@ def generate_from_image(
log.write("opened hunyuan home\n")
if _page_looks_logged_out(page):
raise PermissionError("混元登录凭证已失效,需要重新微信登录。")
raise HunyuanReloginNeeded("混元登录凭证已失效,需要重新微信登录。")
update(event="stage", stage="进入图/文生3D", progress=26)
_enter_studio(page, log)
@@ -552,6 +715,7 @@ def generate_from_image(
submitted = False
for attempt in range(1, 4):
if not _click_generate(page, log=log):
_raise_if_quota(page=page, payloads=generations_bodies)
_dump_debug(page, directory, log, network_hits)
raise RuntimeError("未找到「立即生成」按钮,页面结构可能已变化。")
log.write(f"generate attempt {attempt}/3\n")
@@ -565,15 +729,21 @@ def generate_from_image(
submitted = True
log.write("generations API observed\n")
break
# 提交无响应时优先识别额度弹窗
_raise_if_quota(page=page, payloads=generations_bodies)
log.write("no /creations/generations yet; will retry click\n")
page.wait_for_timeout(1200)
if not submitted:
_raise_if_quota(page=page, payloads=generations_bodies)
_dump_debug(page, directory, log, network_hits)
raise RuntimeError(
"点击「立即生成」后官网未发起生成请求(无 /creations/generations)。"
"请打开混元官网确认额度/协议弹窗后重试。"
"可能是额度不足或协议弹窗未处理;脚本将尝试打开登录页换号。"
)
# generations 返回了但可能是额度错误
_raise_if_quota(page=page, payloads=generations_bodies)
(directory / "hunyuan_generations.json").write_text(
json.dumps(generations_bodies, ensure_ascii=False, indent=2)[:200000],
encoding="utf-8",
@@ -635,12 +805,36 @@ def generate_from_image(
)
context.storage_state(path=str(state_path))
return mesh
except HunyuanQuotaExceeded:
log.write("ERROR: quota exceeded\n")
try:
_dump_debug(page, directory, log, network_hits)
except Exception:
pass
raise
except HunyuanReloginNeeded:
log.write("ERROR: re-login needed\n")
try:
_dump_debug(page, directory, log, network_hits)
except Exception:
pass
raise
except Exception as exc:
log.write(f"ERROR: {exc}\n")
try:
_dump_debug(page, directory, log, network_hits)
except Exception:
pass
# 提交失败且页面有额度提示时,升级为换号登录
if "未发起生成请求" in str(exc) or "立即生成" in str(exc):
try:
_raise_if_quota(page=page, payloads=generations_bodies)
except HunyuanQuotaExceeded:
raise
# 无法确认额度时也当作需换号,方便用户打开登录页处理
raise HunyuanQuotaExceeded(
f"{exc}(已按额度/账号问题处理:将打开登录页换号)"
) from exc
raise
finally:
browser.close()
+14
View File
@@ -0,0 +1,14 @@
"""混元 3D 流程异常:触发交互式重新登录 / 换号。"""
from __future__ import annotations
class HunyuanReloginNeeded(PermissionError):
"""凭证失效或未登录,需要打开登录页重新微信扫码。"""
reason = "auth"
class HunyuanQuotaExceeded(HunyuanReloginNeeded):
"""当前账号额度/次数用尽,需要换号登录后再生成。"""
reason = "quota"

Some files were not shown because too many files have changed in this diff Show More